You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 07:38:06