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

如何修正Python Matplotlib图表中X轴标签的顺序

解决X轴月份顺序混乱的问题

这问题我之前调图表的时候也踩过坑!你的X轴顺序乱掉,本质是因为month列是普通的字符串类型,pandas默认会按照数据中首次出现的顺序来生成轴标签,自然就会出现May到December再跳回January的情况。要改成从January到December的正确顺序,我们只需要把month转换成有序分类变量,强制指定月份的排列逻辑就行。

具体步骤和修改后的代码

首先,我们需要先处理数据里的月份顺序,还要注意你数据里的feburary是拼写错误(正确是February),先统一修正一下,然后定义标准的月份顺序:

import pandas as pd
import matplotlib.pyplot as plt

# 你的销售数据
data = [
    ["May", 2020, 7], ["June", 2020, 2], ["July", 2020, 1], ["August", 2020, 2],
    ["September", 2020, 22], ["October", 2020, 11], ["November", 2020, 6], ["December", 2020, 3],
    ["January", 2019, 3], ["feburary", 2019, 11], ["March", 2019, 65], ["April", 2019, 22],
    ["May", 2019, 33], ["June", 2019, 88], ["July", 2019, 44], ["August", 2019, 12],
    ["September", 2019, 32], ["October", 2019, 54], ["November", 2019, 76], ["December", 2019, 23],
    ["January", 2018, 12], ["feburary", 2018, 32], ["March", 2018, 234], ["April", 2018, 2432],
    ["May", 2018, 432]
]

df = pd.DataFrame(data, columns=["month", "year", "total_sales"])

# 修正February的拼写错误
df["month"] = df["month"].replace("feburary", "February")

# 定义从1月到12月的标准顺序
month_order = [
    "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"
]

# 将month列转换为有序分类,强制使用我们定义的顺序
df["month"] = pd.Categorical(df["month"], categories=month_order, ordered=True)

# 可选:按年份和月份排序,确保每组数据的点是按顺序排列的
df = df.sort_values(["year", "month"])

接下来修改你的绘图函数,现在因为month是有序分类,df['month'].unique()会自动按我们指定的顺序返回,不需要额外调整:

def plot_timeline_data(df):
    fig, ax = plt.subplots()
    # 现在unique()返回的就是January到December的顺序了
    ax.set_xticklabels(df['month'].unique(), rotation=90)
    for name, group in df.groupby('year'):
        ax.plot(group['month'], group['total_sales'], label=name, linestyle='--', marker='o')
    ax.legend()
    plt.tight_layout()
    plt.show()

# 调用绘图函数
plot_timeline_data(df)

为什么这样有效?

  • 把month转换成Categorical类型并指定ordered=True后,pandas会完全尊重我们定义的month_order来排序,不管字符串的字母顺序或者数据中的出现顺序。
  • 排序后的df在分组绘图时,每个年份的月份点也会按正确顺序连接,不会出现跳变的情况。
  • X轴的标签会自动按January到December排列,完美解决你的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:42:31