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

如何在Python中提取Matplotlib饼图的颜色映射字典?

提取Pandas饼图中行星与颜色的映射字典

方法1:从已生成的饼图对象中提取

第一次绘制饼图后,可直接从返回的Axes对象中提取饼块的标签(行星名称)和对应颜色,生成映射字典:

import pandas as pd
import seaborn as sns

# 初始化数据
df = pd.DataFrame({'mass': [0.330, 4.87 , 5.97],
                   'radius': [2439.7, 6051.8, 6378.1]},
                  index=['Mercury', 'Venus', 'Earth'])

# 绘制饼图并获取绘图实例
ax = df.plot.pie(y='mass', figsize=(5, 5), colors=sns.color_palette('Set2'))

# 提取颜色映射:标签(行星名)对应饼块颜色
color_mapping = {patch.get_label(): patch.get_facecolor() for patch in ax.patches}

ax.patches包含饼图的所有饼块元素,get_label()返回行星名称(即DataFrame的索引),get_facecolor()返回饼块的RGBA颜色值,通过字典推导式快速生成映射。


方法2:手动创建固定颜色映射(更可控)

如果后续实验的DataFrame行星顺序可能变化,提前手动生成映射能确保颜色对应关系绝对一致:

# 定义所有涉及的行星列表(需覆盖所有实验中的行星)
all_planets = ['Mercury', 'Venus', 'Earth']
# 生成对应调色板的颜色列表
palette_colors = sns.color_palette('Set2', n_colors=len(all_planets))
# 创建固定映射字典
color_mapping = dict(zip(all_planets, palette_colors))

这种方式无需依赖绘图对象,直接基于行星列表和调色板生成映射,适合循环中统一调用。


循环绘图时的使用示例

拿到color_mapping后,循环处理多个实验DataFrame时,只需按当前DataFrame的索引顺序提取对应颜色即可:

# 模拟多个实验的DataFrame集合
experiment_dataframes = [
    pd.DataFrame({'mass': [0.33, 4.87, 5.97], index=['Mercury', 'Venus', 'Earth']}),
    pd.DataFrame({'mass': [0.35, 4.9, 6.0], index=['Mercury', 'Venus', 'Earth']}),
    # 添加更多实验数据...
]

# 循环生成饼图,保持颜色映射一致
for idx, exp_df in enumerate(experiment_dataframes):
    # 按当前DataFrame的行星顺序提取对应颜色
    plot_colors = [color_mapping[planet] for planet in exp_df.index]
    ax = exp_df.plot.pie(y='mass', figsize=(5,5), colors=plot_colors)
    ax.set_title(f'实验 {idx+1} 行星质量分布')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 17:10:05