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

如何为分类值分配指定颜色并使用Plotly绘制饼图

使用Plotly绘制指定颜色的饼图

我需要基于给定的DataFrame绘制饼图,要求匹配附图样式,为每个Index类别分配指定颜色字典中的对应颜色,且使用Plotly实现(之前用Matplotlib生成的饼图不符合预期)。

原始DataFrame

IndexCategory
SE3
COL2
PE1
DP-PD1
COL1
OTH1

已尝试的Matplotlib代码

import matplotlib.pyplot as plt
import pandas as pd

# assign data of lists.  
data = {'index': ['SE', 'COL', 'PE', 'OTH', 'DP-PD'], 'Category': [3, 2, 1, 1,1]}  

# Create DataFrame  
df = pd.DataFrame(data)
plt.pie(df["Category"], labels = df["Category"],startangle=90)
plt.title("Observation statistics", fontsize = 24)

指定颜色字典

color_map = {'DP-PD': '#1E90FF', 'ID': '#FFA500', 'ENC': '#D3D3D3', 'SE': '#FFFF00',
             'COL': '#FF0000', 'GL': '#32CD32', 'COT': '#0000CD', 'PE': '#A52A2A',
             'FI': '#000000', 'OTH': '#00BFFF'}

解决方案(Plotly实现)

首先对原始DataFrame按Index分组求和,确保每个类别对应正确的累计数值,再用Plotly绘制饼图并绑定指定颜色:

import pandas as pd
import plotly.express as px

# 构建原始DataFrame
raw_data = {'Index': ['SE', 'COL', 'PE', 'DP-PD', 'COL', 'OTH'],
            'Category': [3, 2, 1, 1, 1, 1]}
df = pd.DataFrame(raw_data)

# 按Index分组求和,合并重复类别的数值
agg_df = df.groupby('Index')['Category'].sum().reset_index()

# 指定颜色映射字典
color_map = {'DP-PD': '#1E90FF', 'ID': '#FFA500', 'ENC': '#D3D3D3', 'SE': '#FFFF00',
             'COL': '#FF0000', 'GL': '#32CD32', 'COT': '#0000CD', 'PE': '#A52A2A',
             'FI': '#000000', 'OTH': '#00BFFF'}

# 绘制饼图
fig = px.pie(agg_df, 
             values='Category', 
             names='Index', 
             title='Observation statistics',
             color='Index',
             color_discrete_map=color_map,
             startangle=90)

# 调整标签显示(可根据附图需求修改,示例显示类别+数值+百分比)
fig.update_traces(textposition='inside', textinfo='label+value+percent')

# 调整标题字号
fig.update_layout(title_font_size=24)

# 显示图表
fig.show()

关键说明

  1. 分组聚合处理:原始数据中COL有两行,需合并为累计数值3,保证饼图数据准确
  2. 颜色绑定:通过color_discrete_map参数直接关联指定颜色字典,确保每个Index类别对应预设颜色
  3. 样式对齐:设置startangle=90与你之前的Matplotlib配置一致,同时可根据附图调整标签显示内容

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:50:23