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

如何在Matplotlib中并列展示Pandas日期索引时间序列的夏季数据

三年夏季时间序列数据并列可视化实现方案

核心思路是将不同年份的夏季日期对齐到统一的相对时间轴(比如一年中的月-日或第几天),再按年份分组绘图,就能实现并列展示。以下是具体步骤:

1. 预处理数据:提取年份与相对日期

首先给DataFrame添加年份列,以及用于对齐的相对日期列(二选一即可):

import pandas as pd
import matplotlib.pyplot as plt

# 假设你的DataFrame为df,索引是datetime类型
df['year'] = df.index.year
# 选项1:生成"月-日"格式的字符串(可读性更强)
df['month_day'] = df.index.strftime('%m-%d')
# 选项2:生成一年中的第几天(数值型,更适合连续轴)
df['day_of_year'] = df.index.dayofyear

2. 转换数据格式(可选但推荐)

将数据转为宽格式,让年份成为列名,相对日期作为索引,方便直接绘图:

# 以month_day为索引,年份为列,目标数值列为value
pivot_df = df.pivot(index='month_day', columns='year', values='value')

3. 绘制并列对比图

方式一:Matplotlib原生绘图

plt.figure(figsize=(12, 6))
# 遍历每个年份的数据绘制折线
for year in pivot_df.columns:
    plt.plot(pivot_df.index, pivot_df[year], label=str(year), linewidth=2)

plt.xlabel('夏季日期')
plt.ylabel('指标数值')
plt.title('三年夏季时间序列对比')
plt.legend(title='年份')
# 如果用month_day作为x轴,旋转标签避免重叠
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

方式二:Seaborn简化绘图

如果用Seaborn,可以直接用长格式数据绘图,无需转宽格式:

import seaborn as sns

plt.figure(figsize=(12, 6))
sns.lineplot(data=df, x='month_day', y='value', hue='year', marker='o', linewidth=2)

plt.xlabel('夏季日期')
plt.ylabel('指标数值')
plt.title('三年夏季时间序列对比')
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()

注意事项

  • 若不同年份夏季的日期范围不一致,转换宽格式后会出现NaN,绘图时会自动跳过缺失值,不影响整体展示;
  • 如果需要更精确的日期对齐(比如忽略闰年的差异),可以手动调整day_of_year或使用pd.to_datetime将month_day转为每年的统一日期再处理。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.03 17:12:31