为同一行的子图设置公共 xlabel

Set common xlabel for subplots on the same line

我查看了网站上的几个讨论,但找不到我想要的内容。我想在同一行上将一个公共 xlabel 设置为 2 个子图,如下所示:

我尝试了 set_xlabel()、text(),但第一次没有用,第二次我无法将文本放在底部中心。

我想优化代码,如果有人知道的话。

我的代码:

plt.subplot(121)
plt.barh(range(1, len(y)+1), y)
plt.yticks([i+1.5 for i in range(7)], range(7))
plt.xlim(0, xmax)

plt.ylabel("Y label")

plt.subplot(122)
plt.barh(range(1, len(y2)+1), y2, color="r")
plt.yticks([i+1.5 for i in range(7)], range(7))
plt.xlim(0, xmax)

从例如可以看出this question,可以简单的在图的中间设置一些文字。 (这与图中有多少子图无关)。

plt.gcf().text(0.5,0.04,"common xlabel for subplots on the same line", ha="center")

完整示例:

import matplotlib.pyplot as plt
import numpy as np

y = np.random.randint(100,833, size=(7,2))

plt.subplot(121)
plt.barh(range(1, len(y)+1), y[:,0])
plt.yticks([i+1.5 for i in range(len(y))], range(len(y)))
plt.xlim(0, 1000)

plt.ylabel("Y label")

plt.subplot(122)
plt.barh(range(1, len(y)+1), y[:,1], color="r")
plt.yticks([i+1.5 for i in range(len(y))], range(len(y)))
plt.xlim(0, 1000)

plt.gcf().text(0.5,0.04,"common xlabel for subplots on the same line", ha="center")
plt.show()


另一种选择是创建一个新轴,关闭框架并为其提供标签,例如参见

ax = plt.gcf().add_subplot(111, frameon=False)
ax.tick_params(labelcolor='none', top='off', bottom='off', left='off', right='off')
ax.set_xlabel('common xlabel for subplots on the same line', labelpad=8)