使用 matplotlib 缺少第一个 x 标签

Fen*_*hen 5 python label matplotlib pandas

这是我的数据:

a3=pd.DataFrame({'OfficeName':['a','b','c','d','e','f','g','h'],
                 'Ratio': [0.1,0.15,0.2,0.3,0.2,0.25,0.1,0.4]})
Run Code Online (Sandbox Code Playgroud)

这是我绘制条形图的代码:

fig, ax = plt.subplots()
ind = np.arange(a3.loc[:,'OfficeName'].nunique())    # the x locations for the groups
width = 0.35         # the width of the bars
p1 = ax.bar(ind,a3.loc[:,'Ratio'],width)
ax.set_title('Ratio of refunds to purchases')
ax.set_xticklabels(a3.loc[:,'OfficeName'],ha='center')
#ax.set_xticklabels(['a','b','c','d','e','f','g','h'],ha='center')
ax.set_xlabel('x Group')
ax.set_ylabel('Ratio')
plt.show()
Run Code Online (Sandbox Code Playgroud)

但是,在我的图表中,第一个 x 标签丢失了:

在此输入图像描述

我认为这个问题与Matplotlib不同:将x轴刻度标签向左移动一个位置,因为我什至不需要旋转x标签。

谁能解释为什么会发生这种情况以及如何解决它?

DYZ*_*DYZ 0

有一种更简单的方法可以在 Pandas 中生成条形图:

a3.set_index('OfficeName').plot.bar(width=0.35, legend=False)
plt.xticks(rotation=0, ha='center')
Run Code Online (Sandbox Code Playgroud)

(您仍然需要设置 x 轴和 y 轴标签以及标题。)

  • @FengChen 我知道我有点晚了。然而,仅供参考:我在 X 轴上的标签上遇到了同样的问题,并且 `ax.set_xticks(...)` 完全按照我想要的方式完成了工作。请查看这个问题以弄清楚:/sf/ask/1829227571/ (2认同)