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
相关产品推荐
相关产品推荐

