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

如何在plt.subplots中将X轴日期标签设置为‘月-年’美观格式?

时序分解子图X轴日期改为「月-年」格式的实现方法

我使用seasonal_decompose对df_res_indx进行加法模型的时序分解后,通过plt.subplots创建了4个共享X轴的子图并绘制分解结果,但X轴日期显示格式不符合需求,希望改为「月-年」的美观格式。现有代码如下:

decompose_data = seasonal_decompose(df_res_indx, model='additive')
fig, axes = plt.subplots(ncols=1, nrows=4, sharex=True, figsize=(15, 8))

decompose_data.observed.plot(ax=axes[0], legend=False)
axes[0].set_ylabel('Observed', fontsize=12)

decompose_data.trend.plot(ax=axes[1], legend=False)
axes[1].set_ylabel('Trend', fontsize=12)

decompose_data.seasonal.plot(ax=axes[2], legend=False)
axes[2].set_ylabel('Seasonal', fontsize=12)

decompose_data.resid.plot(ax=axes[3], legend=False)
axes[3].set_ylabel('Residual', fontsize=12)

plt.show()

当前X轴为默认日期格式,显示不够直观美观。


解决方案

借助matplotlib.dates模块的日期格式化工具,即可修改X轴显示格式。修改后的完整代码如下:

from matplotlib.dates import DateFormatter

decompose_data = seasonal_decompose(df_res_indx, model='additive')
fig, axes = plt.subplots(ncols=1, nrows=4, sharex=True, figsize=(15, 8))

decompose_data.observed.plot(ax=axes[0], legend=False)
axes[0].set_ylabel('Observed', fontsize=12)

decompose_data.trend.plot(ax=axes[1], legend=False)
axes[1].set_ylabel('Trend', fontsize=12)

decompose_data.seasonal.plot(ax=axes[2], legend=False)
axes[2].set_ylabel('Seasonal', fontsize=12)

decompose_data.resid.plot(ax=axes[3], legend=False)
axes[3].set_ylabel('Residual', fontsize=12)

# 设置X轴日期格式为「月-年」
date_form = DateFormatter("%m-%Y")
axes[3].xaxis.set_major_formatter(date_form)
# 旋转X轴标签避免文本重叠
plt.xticks(rotation=45)

# 自动调整子图间距优化显示
plt.tight_layout()
plt.show()

关键说明

  • 导入DateFormatter类,通过%m-%Y指定日期格式:%m代表两位月份,%Y代表四位年份
  • 由于子图开启了sharex=True共享X轴,只需对最后一个子图的X轴设置格式化器,即可同步所有子图的X轴显示效果
  • 添加plt.xticks(rotation=45)旋转标签,避免日期文本因过密重叠
  • plt.tight_layout()自动调整子图间距,优化整体排版

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 11:12:53