如何阻止Matplotlib对Python柱状图的X轴进行字母排序?
解决Matplotlib柱状图X轴自动按字母排序的问题
这个问题我碰到过好多次啦——Matplotlib默认会把字符串类型的分类索引当成无序类别,自动按字母顺序重新排列,完全不管你DataFrame里已经排好的顺序!下面给你两种靠谱的解决办法:
方法1:把索引转为带顺序的分类类型(Categorical)
这是最推荐的方式,直接让pandas和Matplotlib都尊重你想要的顺序:
fig3, new_ax = plt.subplots(1,1, figsize=(25/3,5)) summary = tsa.source.sum().sort_values(ascending=False) # 关键步骤:将索引转为分类,指定categories为排序后的索引,开启ordered=True summary.index = pd.Categorical(summary.index, categories=summary.index, ordered=True) new_ax.bar(summary.index, summary.values, color=my_colors) # 后面的自定义函数和设置不变 new_ax.legend() bar_heights(new_ax) simpleaxis(new_ax) # ...其他轴设置
方法2:手动指定X轴位置与标签
如果你不想修改索引类型,也可以直接用数值位置来绘制,再手动替换标签:
fig3, new_ax = plt.subplots(1,1, figsize=(25/3,5)) summary = tsa.source.sum().sort_values(ascending=False) # 用0,1,2...作为X轴的位置 x_positions = range(len(summary)) new_ax.bar(x_positions, summary.values, color=my_colors) # 设置刻度位置和对应的标签 new_ax.set_xticks(x_positions) new_ax.set_xticklabels(summary.index) # 后续操作不变 new_ax.legend() bar_heights(new_ax) simpleaxis(new_ax) # ...其他轴设置
为什么原来的代码不生效?
因为当你的索引是字符串时,Matplotlib会自动将它们识别为无序分类,它会忽略DataFrame里的排序逻辑,自己按字母顺序重新排列这些分类。所以必须通过上面的方式明确告诉它要使用的顺序。
另外提个小技巧:如果用pandas自带的plot.bar()方法,其实会自动保留索引的顺序,但你这里用的是原生Matplotlib的bar,所以需要手动处理~
内容的提问来源于stack exchange,提问作者Martin B
相关产品推荐
相关产品推荐

