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

Python中如何按Jan-Feb-Mar顺序分类排序月份,规范柱状图X轴?

解决Seaborn柱状图月份顺序混乱的问题

有两种简单方法可以让月份按Jan、Feb、Mar……的逻辑顺序排列:

方法一:将月份列转为有序分类类型

先定义标准月份顺序,再把数据中的order_month列转换成有序分类,后续使用该列绘图都会自动遵循这个顺序:

import pandas as pd

# 定义正确的月份顺序
month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

# 将列转为有序分类
boeing_df['order_month'] = pd.Categorical(boeing_df['order_month'], categories=month_order, ordered=True)

# 执行原绘图代码
plt.figure(figsize=(15,10))
sns.countplot(x=boeing_df.order_month);
plt.title('Most Popular Order Month');

方法二:直接在countplot中指定order参数

如果不想修改原数据,可在调用countplot时直接传入月份顺序列表,临时指定X轴排列顺序:

plt.figure(figsize=(15,10))
month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
sns.countplot(x=boeing_df.order_month, order=month_order);
plt.title('Most Popular Order Month');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 05:05:13