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

如何在Python中对图表内的月份名称(Jan、Feb等)进行正确排序

问题原因

你当前的Created_Month列是字符串格式,pandas的groupby操作默认会按照字符串的字典序对分组结果排序,而非实际的时间顺序,因此会出现月份排列错乱的问题。

解决步骤
  • 首先将Created_Month列转换为有序分类类型,手动指定月份的正确排序规则,后续分组、绘图时就会按照预设的时间顺序排列。
  • 额外修正原代码的笔误:你连续写了两次plt.xlabel,第二个应该是plt.ylabel用于设置y轴标签,否则会出现标签显示异常。
修正后完整代码
import pandas as pd
import matplotlib.pyplot as plt

# 定义月份的正确时间顺序
month_order = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
# 将Created_Month转为有序分类类型,指定排序规则
df1['Created_Month'] = pd.Categorical(df1['Created_Month'], categories=month_order, ordered=True)

plt.figure(figsize=(8,4))
# 分组后会自动按照有序分类的预设顺序排列,无需额外排序操作
bymonth = df1.groupby('Created_Month').count().reset_index()
a = bymonth['Created_Month']
b = bymonth['Customer Complaint']

plt.plot(a,b,color='g',linewidth=3,label='max complaints in Jun')
plt.xlabel('Created Month')
plt.ylabel('customer complain')
plt.title("Number of complaints monthly")
plt.text(6.25, 1000, '<--max complaint in Jun', fontsize = 12)
plt.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:15:08