Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly Express Pie Chart color_discrete_map not working

Despite digging over all the web (ok, close) I still can't make this simple pie chart color mapping to work properly.

Thanks to the community, I saw that we have to repeat the color='my_column' parameter (even though it is natively taken in account). Native colors are effectively linked to the label names I chose, this is ok.

This fix worked for many, but not in my situation 🤷 (Python3, VSCode, Jupyter Notebook, Plotly Express).

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', # already tried with RGB values too
                ...
                'null': '#222222'
            })

Tried several color expressions (hexa, RGB, named), color_discrete_sequence (works fine) but still no discrete color mapping.

Half a day on a pie chart color mapping 🤯 and my chart still has quite awful colors... Please any help ?

EDIT: fixed ! The problem came from the call of color='my_column, which should be in this case color='df.index'. Now it works just fine!

like image 581
JulMat Avatar asked Oct 25 '25 06:10

JulMat


1 Answers

Posting this as an answer in case folks don't see your edit. The color needed to be defined as df.index as those were the names being used for labels. Also as the original poster mentioned make sure you have the color parameter added as if you don't the pie chart has no idea which data to color.

fig = px.pie(df,
         values=df.values,
         names=df.index,
         color=df.index,
         color_discrete_map={
            'a': '#038141', # already tried with RGB values too
            ...
            'null': '#222222'
        })
like image 140
Joe Rivera Avatar answered Oct 26 '25 19:10

Joe Rivera