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

Pandas多索引时间序列图中X轴主/次刻度(年份/月份)的格式化方法咨询

解决多索引DataFrame时间序列图的X轴刻度格式化问题

我来帮你搞定这个X轴刻度的问题!你现在的情况是分组后得到了年份+月份的多索引DataFrame,之前的代码把每个索引硬拼成字符串,不仅没法区分主/副刻度,还容易出现冗余信息——其实我们可以用更贴合时间序列的处理方式,两种思路供你选:

方法一:把多索引转成Datetime格式(推荐)

pandas和matplotlib对标准的时间戳格式支持特别好,先把你的多索引转换成datetime类型,之后设置刻度就轻松多了:

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 把多索引的年份+月份转换成datetime格式的单索引
# 这里用每月第一天作为时间戳,你也可以用月末日期(和原始数据保持一致)
df_groupby.index = pd.to_datetime([f"{year}-{month}-01" for year, month in df_groupby.index])

# 开始绘图
fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(df_groupby['Dress'])

# 设置主刻度:每年显示一次,格式为年份
ax.xaxis.set_major_locator(mdates.YearLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y'))

# 设置次刻度:每个月显示一次,格式可以选数字'%m'或者月份缩写'%b'
ax.xaxis.set_minor_locator(mdates.MonthLocator())
ax.xaxis.set_minor_formatter(mdates.DateFormatter('%m'))

# 调整标签样式,避免重叠
plt.setp(ax.get_xticklabels(), rotation=0, ha='center')  # 主刻度(年份)居中显示
plt.setp(ax.get_xticklabels(minor=True), rotation=45, ha='right')  # 次刻度(月份)右对齐

plt.title('五年间连衣裙月度销量趋势')
plt.ylabel('销量数量')
plt.xlabel('日期')
plt.tight_layout()
plt.show()

这种方法的好处是完全利用了时间序列的内置工具,不需要手动计算刻度位置,后续如果要做时间相关的分析(比如滚动窗口)也更方便。

方法二:直接处理多索引(不修改数据结构)

如果你不想改变现有的多索引结构,也可以手动指定主/副刻度的位置和标签:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(figsize=(10, 6))
ax.plot(df_groupby['Dress'])

# 获取所有索引的列表
index_list = df_groupby.index.tolist()

# 找到每年第一个月份的位置,作为主刻度的位置
year_positions = [i for i, (year, month) in enumerate(index_list) if month == 1]
# 提取对应的年份作为主刻度标签
year_labels = [year for year, month in index_list if month == 1]

# 设置主刻度:每年第一个月的位置,显示年份
ax.set_xticks(year_positions)
ax.set_xticklabels(year_labels, rotation=0, ha='center')

# 设置次刻度:所有月份的位置,显示月份数字
ax.set_xticks(range(len(index_list)), minor=True)
ax.set_xticklabels([month for year, month in index_list], minor=True, rotation=45, ha='right')

# 可选:隐藏次刻度的短横线,让图表更整洁
ax.tick_params(axis='x', which='minor', length=0)

plt.title('五年间连衣裙月度销量趋势')
plt.ylabel('销量数量')
plt.xlabel('年月')
plt.tight_layout()
plt.show()

这个方法适合不想改动原始分组结果的场景,完全手动控制刻度的显示逻辑。

两种方法都能解决你之前的问题——主刻度显示年份,次刻度显示月份,而且不会出现冗余的日期信息,你可以根据自己的需求选~

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 19:52:32