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

Plotly Express饼图color_discrete_map不生效问题求助及解决

解决Plotly Express饼图color_discrete_map颜色映射无效问题

问题场景

在Python3+VSCode+Jupyter Notebook环境中,使用Plotly Express绘制饼图时,color_discrete_map参数无法正常生效。即便参考社区方案重复设置color='my_column',尝试了十六进制、RGB、命名颜色等多种颜色格式,color_discrete_sequence能正常工作,但color_discrete_map始终不生效。

用户初始代码示例:

import pandas as pd
import plotly.express as px

# render in GitHub & NBViewer
import plotly.io as pio
pio.renderers.default = 'notebook_connected'

# 省略数据处理步骤
df = data['my_column'].value_counts(dropna=False).sort_index()

fig = px.pie(df,
             values=df.values,
             names=df.index,
             color='my_column',
             color_discrete_map={
                'a': '#038141', # 已尝试过RGB格式
                ...
                'null': '#222222'
            })

解决方法

问题核心是color参数的取值错误:原代码中指定color='my_column',但此时的df是value_counts的结果,不存在名为my_column的列,正确的做法是将color参数设置为df.index(因为df.index对应原my_column的所有取值)。

修改后的关键代码片段:

fig = px.pie(df,
             values=df.values,
             names=df.index,
             color=df.index,  # 此处修改为df.index
             color_discrete_map={
                'a': '#038141',
                ...
                'null': '#222222'
            })

修改后color_discrete_map即可按照配置的键值对正常映射颜色。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 19:43:11