一般来说,如果你要显示的两个变量具有不同的单位或范围,你需要使用两个带有共享Y轴的子图。这类似于@regdoug的回答,但最好显式共享Y轴以确保数据保持对齐(例如在此示例中尝试缩放/平移)。
例如:
import matplotlib.pyplot as plt
y = range(20)
x1 = range(20)
x2 = range(0, 200, 10)
fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].barh(y, x1, align='center', color='gray')
axes[1].barh(y, x2, align='center', color='gray')
axes[0].invert_xaxis()
plt.show()
如果您想更精确地复制您所链接的问题中显示的示例(我将省略灰色背景和白色网格,但如果您喜欢,这些很容易添加):
import numpy as np
import matplotlib.pyplot as plt
states = ["AK", "TX", "CA", "MT", "NM", "AZ", "NV", "CO", "OR", "WY", "MI",
"MN", "UT", "ID", "KS", "NE", "SD", "WA", "ND", "OK"]
staff = np.array([20, 30, 40, 10, 15, 35, 18, 25, 22, 7, 12, 22, 3, 4, 5, 8,
14, 28, 24, 32])
sales = staff * (20 + 10 * np.random.random(staff.size))
idx = staff.argsort()
states, staff, sales = [np.take(x, idx) for x in [states, staff, sales]]
y = np.arange(sales.size)
fig, axes = plt.subplots(ncols=2, sharey=True)
axes[0].barh(y, staff, align='center', color='gray', zorder=10)
axes[0].set(title='Number of sales staff')
axes[1].barh(y, sales, align='center', color='gray', zorder=10)
axes[1].set(title='Sales (x $1000)')
axes[0].invert_xaxis()
axes[0].set(yticks=y, yticklabels=states)
axes[0].yaxis.tick_right()
for ax in axes.flat:
ax.margins(0.03)
ax.grid(True)
fig.tight_layout()
fig.subplots_adjust(wspace=0.09)
plt.show()
![在此输入图像描述](https://istack.dev59.com/sSd6x.webp)
需要注意的是,我并没有正确对齐y轴刻度标签。虽然可以这样做,但比你想象的要麻烦得多。因此,如果您真的希望y轴刻度标签总是完美地居中于图形的中间位置,最简单的方法是以不同的方式绘制它们。而不是使用axes[0].set(yticks=y, yticklabels=states)
,您可以采取类似以下的方式:
axes[0].set(yticks=y, yticklabels=[])
for yloc, state in zip(y, states):
axes[0].annotate(state, (0.5, yloc), xycoords=('figure fraction', 'data'),
ha='center', va='center')