Matplotlib循环生成子图绘制各年月均温的报错修复与可视化问题
实现方案
报错原因
现有代码的报错来源于for i in enumerate(df.year.unique())写法,enumerate返回的是(索引, 年份值)的元组,直接将元组与整数做除法运算会触发类型错误。原有子图布局逻辑仅支持年份数为4的倍数的场景,三层循环逻辑冗余,不符合需求。
核心适配逻辑
- 子图布局:固定2列,通过向上取整计算行数,自动适配奇数、偶数年份场景
- 配色规则:以当年平均温度为阈值,低于阈值的月份温度用蓝色展示,高于阈值的用红色展示
- 图例配置:全局统一添加高低温对应配色的图例
完整可运行代码
import numpy as np import matplotlib.pyplot as plt import pandas as pd import math from matplotlib.patches import Patch # 此处为模拟数据,可替换为你的真实业务数据 d = {'year': [2001, 2001, 2001, 2001, 2002, 2002, 2002, 2002, 2003, 2003, 2003, 2003], # 额外增加2003年测试奇数年适配效果 'month': [1, 2,3,4, 1,2,3,4, 1,2,3,4], 'temperature': [10,20,15,20, 20,10,5,10, 12,18,22,16]} df = pd.DataFrame(data=d) years = df['year'].unique() year_cnt = len(years) # 固定2列,自动计算行数适配不同年份数量 cols = 2 rows = math.ceil(year_cnt / cols) fig, axs = plt.subplots(rows, cols, figsize=(10, 4*rows), tight_layout=True) # 把轴数组转成一维,适配各种行列数场景的索引调用 axs = axs.flatten() for idx, year in enumerate(years): ax = axs[idx] # 提取当年各月平均温度 year_data = df[df['year'] == year].groupby('month')['temperature'].mean().reset_index() months = year_data['month'] temps = year_data['temperature'] # 计算当年平均温度作为高低温分界 year_avg = temps.mean() # 生成对应配色 colors = ['#1f77b4' if t < year_avg else '#ff4b33' for t in temps] # 绘制柱状图 ax.bar(months, temps, color=colors) # 子图基础配置 ax.set_title(f'{year}年各月平均温度') ax.set_xlabel('月份') ax.set_ylabel('温度(℃)') # 隐藏奇数年场景下多余的空轴 for idx in range(year_cnt, len(axs)): axs[idx].axis('off') # 全局添加图例 legend_elements = [Patch(facecolor='#1f77b4', label='低温(低于当年平均)'), Patch(facecolor='#ff4b33', label='高温(高于当年平均)')] fig.legend(handles=legend_elements, loc='upper right') plt.show()
内容的提问来源于stack exchange,提问作者Test
相关产品推荐
相关产品推荐

