如何将不同年份的温度时间序列按相同月份对齐绘制在同一折线图中
多年份月度温度同图对比解决方案
1. 数据预处理(拆分年份、月度公共维度)
首先完成时间字段的解析和维度拆分,解决无法提取年度月度子集的问题:
import pandas as pd import matplotlib.pyplot as plt # 读取本地存储的温度数据集 df = pd.read_csv("temp.csv") # 转换时间列为标准datetime格式,需替换为你实际的时间列名 df["date"] = pd.to_datetime(df["date"]) # 拆分独立的年份、月份字段,作为后续分组和对齐的维度 df["year"] = df["date"].dt.year # 可生成月份名称作为x轴标签,可读性更强 df["month_name"] = df["date"].dt.strftime("%b")
如果存在部分月份数据缺失的情况,可以先做重采样补全,避免后续折线断裂:
# 按月份重采样,取月度温度均值补全缺失值 df = df.set_index("date").resample("M").mean(numeric_only=True).reset_index() # 补全后重新生成year、month_name字段即可 df["year"] = df["date"].dt.year df["month_name"] = df["date"].dt.strftime("%b")
2. 按年份分组绘制对齐折线
以月份为公共x轴,遍历每一年的数据单独绘制折线,即可实现多年份同图对齐展示的效果:
plt.figure(figsize=(12, 6)) # 遍历所有存在数据的年份 for target_year in df["year"].unique(): # 提取单年份的月度温度子集 year_temp = df[df["year"] == target_year] # 绘制折线,标注年份作为图例 plt.plot(year_temp["month_name"], year_temp["temp"], label=str(target_year), marker='o', alpha=0.7) # 图表样式配置 plt.xlabel("月份") plt.ylabel("温度") plt.title("不同年份月度温度对比") plt.legend(ncol=3) plt.grid(alpha=0.3) plt.show()
如果需要突出某一年的温度趋势,可以单独调整该折线的样式:
for target_year in df["year"].unique(): year_temp = df[df["year"] == target_year] if target_year == 2023: # 替换为你需要高亮的年份 plt.plot(year_temp["month_name"], year_temp["temp"], label=str(target_year), marker='o', linewidth=3, color='#c82423') else: plt.plot(year_temp["month_name"], year_temp["temp"], label=str(target_year), marker='o', alpha=0.5, color='gray')
内容的提问来源于stack exchange,提问作者Gonzalo de Quesada
相关产品推荐
相关产品推荐

