如何使用Matplotlib或Seaborn为分组条形图按指定类别生成对应图例
解决方案
直接基于你现有的matplotlib绘图逻辑手动构造图例即可,不会额外增加性能损耗,完全匹配你指定的颜色映射:
实现步骤
- 从已排序的
tmp_df中提取Class和Color的唯一映射关系,避免重复条目 - 使用matplotlib的
Patch构造每个类别的图例句柄 - 调用
ax.legend()传入构造好的句柄即可生成图例
完整代码
import numpy as np import pandas as pd import matplotlib.pyplot as plt from matplotlib.patches import Patch # 示例数据集 df = pd.DataFrame({ 'tic': {0: 'A', 1: 'AAPL', 2: 'ABC', 3: 'ABT', 4: 'ADBE', 5: 'ADI', 6: 'ADM', 7: 'ADP', 8: 'ADSK', 9: 'AEE'}, 'Class': {0: 'Manufacturing', 1: 'Tech', 2: 'Trade', 3: 'Manufacturing', 4: 'Services', 5: 'Tech', 6: 'Manufacturing', 7: 'Services', 8: 'Services', 9: 'Electricity and Transportation'}, 'Color': {0: 'blue', 1: 'teal', 2: 'purple', 3: 'blue', 4: 'red', 5: 'teal', 6: 'blue', 7: 'red', 8: 'red', 9: 'orange'}, 'Pooled 1': {0: 0.0643791550056838, 1: 0.05022103288830682, 2: 0.039223739393748916, 3: 0.036366693834970217, 4: 0.05772708899447428, 5: 0.05969899935101172, 6: 0.04568101605219955, 7: 0.04542272002937567, 8: 0.07138013872431757, 9: 0.029987722053015278} }) # 原有绘图逻辑 fig, axs = plt.subplots(1, 1, figsize=(24, 5)) tmp_df = df.sort_values('Class') plt.bar(np.arange(len(tmp_df)), tmp_df['Pooled 1'], color=tmp_df['Color']) # 新增图例生成逻辑 # 提取唯一的类别-颜色映射 class_color_mapping = tmp_df.drop_duplicates('Class')[['Class', 'Color']].set_index('Class')['Color'].to_dict() # 构造图例句柄 legend_handles = [Patch(facecolor=color, label=class_name) for class_name, color in class_color_mapping.items()] # 添加图例,可自由调整位置、标题等样式 axs.legend(handles=legend_handles, loc='upper right', title='类别', fontsize=12) plt.show()
方案优势
- 完全保留原生matplotlib的高性能,全量数据集绘制速度和你原有代码一致,不会出现seaborn的卡顿问题
- 自动匹配数据中的类别和颜色对应关系,不需要手动硬编码映射规则
- 支持所有matplotlib图例的自定义参数,可自由调整位置、大小、标题等样式
内容的提问来源于stack exchange,提问作者Raul Guarini Riva
相关产品推荐
相关产品推荐

