如何按每月天/年中日分组时序数据并绘制跨年度对比图表?
解决方案:时间序列分组与GHCN气温数据可视化优化
需求一:按每月天数分组并设置绘图X轴
先确保你的DataFrame日期列是datetime类型(如果不是,先执行转换):
import pandas as pd # 假设日期列名为date df['date'] = pd.to_datetime(df['date']) df.set_index('date', inplace=True)
步骤1:提取每月天数并分组
添加一列存储每月的天数,再按该列分组(聚合方式按需选择,比如均值、总和):
# 提取每月的天数 df['day_of_month'] = df.index.day # 按每月天数分组,计算目标列的均值 grouped_data = df.groupby('day_of_month')['target_column'].mean()
步骤2:绘图并设置X轴为每月天数
直接用分组后的数据绘图,X轴会自动对应每月天数:
import matplotlib.pyplot as plt plt.figure(figsize=(10, 6)) grouped_data.plot(kind='line', marker='o') plt.xlabel('每月天数') plt.ylabel('目标指标值') plt.title('按每月天数分组的指标变化趋势') plt.grid(True) plt.show()
如果不需要聚合,只是把原始数据的X轴设为每月天数,直接用散点或折线图:
plt.figure(figsize=(10, 6)) plt.scatter(df.index.day, df['target_column']) plt.xlabel('每月天数') plt.ylabel('目标指标值') plt.show()
需求二:GHCN日度气温按年中日分组对比
注意:GHCN的TMAX单位是百分之一摄氏度,需除以10转换为℃。
步骤1:提取年中日标识
用月-日组合作为年中日的唯一标识(比一年中的第几天更直观):
# 先确保date列是datetime类型 df['date'] = pd.to_datetime(df['date']) # 提取月-日字符串作为分组键 df['month_day'] = df['date'].dt.strftime('%m-%d') # 提取年份用于区分不同年份的数据 df['year'] = df['date'].dt.year # 转换TMAX为摄氏度 df['tmax_c'] = df['TMAX'] / 10
步骤2:可视化各年份对应日期的气温对比
方法1:折线图(每条线对应一个年份)
适合观察每年同一日期的气温变化趋势:
import seaborn as sns plt.figure(figsize=(12, 6)) sns.lineplot(data=df, x='month_day', y='tmax_c', hue='year', marker='o', palette='tab10') plt.xlabel('日期(月-日)') plt.ylabel('最高气温(℃)') plt.title('1991-2009年8月26日至9月3日最高气温对比') # 把图例移到图外避免遮挡 plt.legend(title='年份', bbox_to_anchor=(1.05, 1), loc='upper left') plt.grid(axis='y') plt.show()
方法2:箱线图(查看同一日期的气温分布)
适合对比各日期的气温离散程度:
plt.figure(figsize=(10, 6)) sns.boxplot(data=df, x='month_day', y='tmax_c') plt.xlabel('日期(月-日)') plt.ylabel('最高气温(℃)') plt.title('1991-2009年8月26日至9月3日最高气温分布') plt.grid(axis='y') plt.show()
方法3:聚合后对比每年同一天的平均气温
如果需要看每年同一天的平均气温:
# 按月-日和年份分组,计算平均气温 avg_tmax = df.groupby(['month_day', 'year'])['tmax_c'].mean().unstack() plt.figure(figsize=(12, 6)) avg_tmax.plot(kind='line', marker='o') plt.xlabel('日期(月-日)') plt.ylabel('平均最高气温(℃)') plt.title('1991-2009年8月26日至9月3日平均最高气温对比') plt.legend(title='年份', bbox_to_anchor=(1.05, 1), loc='upper left') plt.grid(axis='y') plt.show()
内容的提问来源于stack exchange,提问作者Kyle Pennell
相关产品推荐
相关产品推荐

