You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Matplotlib多子图饼图的颜色映射到单个图例

解决Matplotlib多饼图统一图例颜色匹配问题

核心思路

既然已有固定的厂商-颜色映射字典,直接基于该字典控制每个饼图切片的颜色,绕过Matplotlib默认颜色循环;统一图例通过自定义图例元素(Patch)生成,完全匹配预定义的颜色映射,不受子图绘制顺序和切片数量影响。

可复现代码

import matplotlib.pyplot as plt
from matplotlib.patches import Patch

# 固定的厂商-颜色映射字典
vendor_color_map = {
    "厂商A": "#FF5733",
    "厂商B": "#33FF57",
    "厂商C": "#3357FF",
    "厂商D": "#FF33A6",
    "厂商E": "#FFC300"
}

# 构造示例数据:每个子图的厂商和对应占比
subplot_data = [
    {"厂商A": 30, "厂商C": 25, "厂商E": 45},
    {"厂商B": 50, "厂商D": 30, "厂商A": 20},
    {"厂商C": 10, "厂商D": 40, "厂商E": 25, "厂商B": 25}
]

# 创建画布和子图
fig, axes = plt.subplots(1, 3, figsize=(12, 4))

# 遍历绘制每个饼图
for ax, data in zip(axes, subplot_data):
    vendors = list(data.keys())
    sizes = list(data.values())
    # 从映射字典中获取当前饼图对应厂商的颜色
    colors = [vendor_color_map[v] for v in vendors]
    ax.pie(sizes, labels=vendors, colors=colors, autopct='%1.1f%%')
    ax.set_title(f"子图{axes.tolist().index(ax)+1}")

# 生成统一图例:基于颜色映射字典创建Patch元素
legend_elements = [Patch(facecolor=color, label=vendor) 
                   for vendor, color in vendor_color_map.items()]
fig.legend(handles=legend_elements, loc="lower center", ncol=5, bbox_to_anchor=(0.5, -0.1))

plt.tight_layout()
plt.show()

关键说明

  • 绘制每个饼图时,通过[vendor_color_map[v] for v in vendors]严格匹配当前厂商对应的颜色,彻底避免颜色循环导致的错位
  • 统一图例直接使用预定义的映射字典生成Patch对象,确保图例的名称和颜色完全对应固定列表,和子图中实际绘制的切片数量无关
  • 通过bbox_to_anchor调整图例位置,避免遮挡饼图

内容的提问来源于stack exchange,提问作者Kgrover3

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 09:30:41