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

matplotlib xtick格式化:周度时序数据x轴仅显示年份刻度设置

matplotlib 按周时间序列x轴仅显示年份解决方案

问题根源

你当前直接使用week-year字符串作为x轴绘制折线,matplotlib会将每个字符串识别为独立的分类刻度,186周对应186个分类刻度全部挤在一起自然无法辨认。手动设置年份标签时会因为标签数量和分类刻度数量不匹配报错。

解决方法

改用日期类型的Week_Start_Date作为x轴,matplotlib的日期格式化工具可以自动适配时间维度的刻度,不需要手动匹配数据点数量,修改后代码如下:

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

# 先把日期列转成datetime格式,若已经是日期类型可跳过
organic_search['Week_Start_Date'] = pd.to_datetime(organic_search['Week_Start_Date'])

# 按周聚合数据,保留每周起始日期
weekly_revenue = organic_search.groupby(['Week_Start_Date'], as_index=False)['Amount'].sum()
# 按日期排序避免折线错乱
weekly_revenue = weekly_revenue.sort_values('Week_Start_Date')

fig, ax = plt.subplots(1,1,figsize=[10, 5])
plt.plot(weekly_revenue['Week_Start_Date'], weekly_revenue['Amount'], color='g')
plt.title('Organic Search Revenue Time Series')

# 原有y轴格式化逻辑保留
fmt = '${x:,.0f}'
tick = mtick.StrMethodFormatter(fmt)
ax.yaxis.set_major_formatter(tick)

# x轴仅显示年份配置
ax.xaxis.set_major_locator(mdates.YearLocator()) # 主刻度定位到每年的位置
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y')) # 刻度值仅显示四位年份

plt.ylabel('Revenue')
plt.xlabel('Year')
plt.grid(True)
# 可选:自动旋转x轴刻度避免重叠
fig.autofmt_xdate()
plt.show()

该方案会完全保留按周的折线走势,仅修改x轴刻度显示逻辑,不会出现图表压缩、标签不匹配的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 18:09:03