【问题标题】:the first x label is missing using matplotlib使用 matplotlib 缺少第一个 x 标签
【发布时间】:2018-12-31 14:07:14
【问题描述】:

这是我的数据:

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]})

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

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

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

我认为这个问题与Matplotlib: Move x-axis tick labels one position to left 不一样,因为我什至不需要旋转 x 标签。

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

【问题讨论】:

  • 切勿在未指定标签位置的情况下使用ax.set_ticklabels,即ax.set_ticks

标签: python pandas matplotlib label


【解决方案1】:

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

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

(还是需要设置x和y轴标签和标题。)

【讨论】:

  • 谢谢。你能告诉我为什么会出现我的问题吗?
  • 我只能说由于某种原因ax.bar() 在位置-1 处添加了另一个刻度(请致电ax.get_xticks() 亲自查看!))标签“a”分配给该刻度并且不在图表之列。
  • 谢谢。这真的很有帮助
  • @FengChen 我知道我来晚了。但是,仅供参考:我在 X 轴上的标签上遇到了同样的问题,ax.set_xticks(...) 完全按照我想要的方式完成了这项工作。请查看此问题以清楚说明:stackoverflow.com/questions/26131822/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-08
  • 2020-06-12
  • 1970-01-01
相关资源
最近更新 更多