Matplotlib绘制带冬季时段背景多边形的时间序列图
实现方法
你可以用Matplotlib的ax.axvspan()方法给指定时间段添加底层彩色背景,通过筛选每年12月到次年2月的时段批量添加即可,完整可运行代码如下:
import pandas as pd import numpy as np import matplotlib.pyplot as plt # 原有基础代码 dates = pd.date_range("2000-01-01", "2004-01-01", freq="D") df = pd.DataFrame({"y": np.random.random(len(dates))}, index=dates) f, ax = plt.subplots(figsize=(12, 4)) # 折线zorder设为2,保证在背景图层上方 ax.plot(df.index, df["y"], zorder=2) # 提取时间的年份、月份字段用于筛选冬季 df['year'] = df.index.year df['month'] = df.index.month # 补充第一个年份的1-2月冬季时段(2000年1-2月) first_year = df['year'].min() first_feb_end = pd.Timestamp(f"{first_year}-02-29") if first_year % 4 == 0 else pd.Timestamp(f"{first_year}-02-28") ax.axvspan(pd.Timestamp(f"{first_year}-01-01"), first_feb_end, color='lightblue', alpha=0.3, zorder=1) # 遍历每一年,生成当年12月到次年2月的冬季背景 for year in df['year'].unique(): # 当年12月的起止时间 dec_start = pd.Timestamp(f"{year}-12-01") dec_end = pd.Timestamp(f"{year}-12-31") # 次年2月的结束时间,兼容闰年 next_year_feb_end = pd.Timestamp(f"{year+1}-02-29") if (year+1) % 4 == 0 else pd.Timestamp(f"{year+1}-02-28") # 仅添加在数据集时间范围内的时段 if dec_start <= df.index.max(): ax.axvspan(dec_start, dec_end, color='lightblue', alpha=0.3, zorder=1) if pd.Timestamp(f"{year+1}-01-01") <= df.index.max(): ax.axvspan(pd.Timestamp(f"{year+1}-01-01"), next_year_feb_end, color='lightblue', alpha=0.3, zorder=1) plt.show()
自定义调整说明
- 可修改
color参数更换背景色,示例使用的是浅蓝色lightblue - 可修改
alpha参数调整背景透明度,数值越小越透明,避免遮挡坐标轴信息 zorder参数控制图层优先级,数值越小图层越靠下,保证背景不会遮挡折线
内容的提问来源于stack exchange,提问作者Tommy Lees
相关产品推荐
相关产品推荐

