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

如何按月份升序排序苹果销量堆叠条形图(Stacked Bar Graph)

解决堆叠条形图月份按升序排列的问题

默认情况下,字符串类型的月份会按字母顺序排序(比如April会排在最前面),要让图表里的月份按自然顺序(一月→二月→三月→四月)排列,你可以把Month列转换成有序分类类型,指定正确的月份顺序后再进行分组绘图操作。

修改后的完整代码:

import pandas as pd

# 定义月份的正确顺序
month_order = ['January', 'February', 'March', 'April']

# 将Month列转为有序分类,强制指定排序规则
v['Month'] = pd.Categorical(v['Month'], categories=month_order, ordered=True)

# 执行分组聚合并绘制堆叠条形图
(v[['Type Apple','Month', 'freq']]
 .groupby(['Month', 'Type Apple'])
 .agg('count')
 .unstack()
 .plot.barh(stacked=True)
 .legend(loc='upper left', bbox_to_anchor=(1.0, 1.0)))

关键说明:

  • 通过pd.Categorical把Month列设置为有序分类,categories参数传入我们想要的月份顺序,ordered=True确保后续分组和绘图时严格遵循这个顺序。
  • 执行完类型转换后,再运行你原来的分组绘图逻辑,生成的条形图就会按一月到四月的升序排列了。

内容的提问来源于stack exchange,提问作者light

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 09:51:05