Matplotlib 为同一行上的子批次设置公共xlabel

Matplotlib 为同一行上的子批次设置公共xlabel,matplotlib,label,subplot,Matplotlib,Label,Subplot,我查看了网站上的几个讨论,但我找不到我想要的。我想将一个公共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.

我查看了网站上的几个讨论,但我找不到我想要的。我想将一个公共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)

如从图中可以看到的,你可以简单地在图中间设置一些文本(这不取决于图中有多少个子图)。 完整示例:

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()

另一个选项是在框架关闭的情况下创建新轴,并为其提供标签,请参见


可能的副本已检查并已尝试,但不起作用。对于3x3子地块,很容易将xlabel居中,但对于1x2子地块,我不知道。请解释为什么/如何“不起作用”任何数量子地块的公认答案。所以3x3不容易,1x2不容易。@Diziet Asahi,它给了我一个错误。实际上,当我使用text()时,文本被叠加到图形上,即使我更改x和y坐标,它也没有放在我想要的地方。可能是因为您添加了gcf()。
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)