多级索引DataFrame绘图图例与图表颜色不匹配问题排查
问题:多级索引DataFrame绘图时图例与条形颜色不匹配
数据样本
cluster PredictionDate FGCI 1.5 2022-04-11 0.778682 2022-04-11 1.686295 2022-05-10 1.689775 2022-05-10 0.780289 2022-06-09 0.781591 2022-06-09 1.692596 FGCI 2.0 2022-04-11 1.176237 2022-04-11 2.592334 2022-04-11 2.071005 2022-04-11 6.745330 2022-04-11 1.089879 2022-05-10 6.746528 2022-05-10 1.176446 2022-05-10 2.071373 2022-05-10 2.592795 2022-05-10 1.090073 2022-06-09 2.071265 2022-06-09 2.592660 2022-06-09 6.746177 2022-06-09 1.176384 2022-06-09 1.090016 Name: weighted_MAPE_contrib, dtype: float64
原代码问题
原代码按cluster分组循环,每次循环重复使用['red', 'green', 'blue']颜色列表,导致颜色分配混乱;同时图例未与实际颜色绑定,最终出现颜色与标签不匹配的问题。
修正方案
核心思路
- 给每个
PredictionDate绑定固定颜色,避免颜色重复分配 - 手动创建图例元素,确保标签和颜色一一对应
- 按数据点的日期匹配对应颜色,保证同日期条形颜色一致
修正后的代码
import matplotlib.pyplot as plt from matplotlib.patches import Patch # 定义日期与颜色的固定映射 date_color_map = { '2022-04-11': 'red', '2022-05-10': 'green', '2022-06-09': 'blue' } fig, ax = plt.subplots(figsize=(10,8)) # 遍历每个cluster的数据 for cluster, cluster_data in new_merged.groupby(level=0): # 为每个数据点匹配对应日期的颜色 colors = [date_color_map[str(date)] for date in cluster_data.index.get_level_values('PredictionDate')] # 绘制条形图 ax.bar( cluster_data.index.get_level_values('cluster').values, cluster_data['weighted_MAPE_contrib'], color=colors ) # 设置图表属性 ax.set_ylabel('UPB-Weighted Mean Absolute Percentage Error') ax.set_title('UPB-Weighted MAPE on Cluster Level for Grouped Vintages') locs, labels = plt.xticks() plt.setp(labels, rotation=90) # 手动创建匹配的图例 legend_elements = [Patch(facecolor=color, label=date) for date, color in date_color_map.items()] ax.legend(handles=legend_elements, title='PredictionDate') plt.show()
关键修改点
- 固定颜色映射:用字典明确每个日期对应的颜色,彻底避免循环中颜色分配混乱的问题
- 动态颜色匹配:根据每个数据点的
PredictionDate从映射字典中获取颜色,保证同日期条形颜色统一 - 手动创建图例:通过
Patch对象直接绑定日期与对应颜色,解决图例与图表颜色不匹配的核心问题
内容的提问来源于stack exchange,提问作者hulio_entredas
相关产品推荐
相关产品推荐

