将轴顶部的 xticks 与 matplotlib 中的条对齐

Align xticks on top of axes with bars in matplotlib

我有以下条形图。

我希望图表顶部 x 轴上的 xticks 与条形对齐。

因此,我希望它们的间距不是均匀 [105, 20, 75, ...],而是让 105 在第一个柱上方,4 在最后一个柱上方,依此类推。

如何做到这一点?

示例代码(生成上图):

from matplotlib import pyplot as plt

x = [10, 20, 30, 40, 90]
y = [7, 8, 12, 25, 50]
other = [105, 20, 75, 20, 4]

fig,ax = plt.subplots()
plt.bar(x,y)

ax.set_title('title', y=1.04)
ax.set_xlabel('x label')
ax.set_ylabel('y label')

ax2 = ax.twiny()
ax2.set_xticklabels(ax2.xaxis.get_majorticklabels(), rotation=90)
ax2.set_xticklabels(other)

plt.show()

您想要做的是使用 ax2.set_xticks(locations). Also, you want to ensure that the xlims are the same for both ax and ax2. This guarantees that the ticks will line up with the bars. We can do this with set_xlim and get_xlim 手动指定 xtick 位置。如果我们修改代码的 ax2 部分并将这些更改考虑在内,我们将得到以下结果。

ax2 = ax.twiny()

# Ensure that the x limits are the same
ax2.set_xlim(ax.get_xlim())

# Set the labels to be the values we want and rotated
ax2.set_xticklabels(other, rotation=90)

# Place the xticks on ax2 at the bar centers
ax2.set_xticks(x)