1
votes

I am plotting a series of 3 pie charts using make_subplots and go.Pie. I want to eventually put these in a dash app where the user can filter the data and the figure will update. How can I map specific colors to variables so that Male is always blue, Female is always pink, etc. You can do this with plotly express with color_discrete_map but plotly express doesn't support subplots afaik.

Here is an example df that I make the gender pie chart from. The other dfs have the same format just different values.

    Gender  ACC_ID  percent
0   Female  57647   57.0
1   Male    37715   37.0
2   Other   5875    6.0

And here is the code I use to make the figures

fig = make_subplots(rows=1, cols=3, specs=[[{'type':'domain'}, {'type':'domain'},{'type':'domain'}]])
fig.add_trace(go.Pie(labels=age["Age_Group"], values=age["percent"],customdata=age["ACC_ID"], textinfo='label+percent',insidetextorientation='horizontal', textfont=dict(color='#000000'), marker_colors=px.colors.qualitative.Plotly),
              1, 1)
fig.add_trace(go.Pie(labels=gender["Gender"], values=gender["percent"], customdata=gender["ACC_ID"],textinfo='label+percent',insidetextorientation='horizontal',textfont=dict(color='#000000'),marker_colors=px.colors.qualitative.Plotly),
              1, 2)
fig.add_trace(go.Pie(labels=sample["Sample_Type"], values=sample["percent"], customdata=sample["ACC_ID"],textinfo='label+percent',texttemplate='%{label}<br>%{percent:.1%f}',insidetextorientation='horizontal',textfont=dict(color='#000000'),marker_colors=px.colors.qualitative.Prism),
              1, 3)


fig.update_traces(hole=.4, hoverinfo='label+percent', hovertemplate="<b>%{label}</b><br>Percent: %{percent}<br>Total: %{customdata}<extra></extra>")

fig.update_layout(
    showlegend=False,
    uniformtext_minsize=14, 
    uniformtext_mode='hide',

    annotations=[dict(text='Age', x=0.13, y=0.5, font_size=20, showarrow=False, font=dict(color="black")),
                 dict(text='Gender', x=0.5, y=0.5, font_size=20, showarrow=False,font=dict(color="black")),
                 dict(text='Sample', x=0.879, y=0.5, font_size=20, showarrow=False,font=dict(color="black"))])
    

plot(fig)
2

2 Answers

1
votes

It seems that color_discrete_map is what you're after.

You can create a dictionary with the desired tags as keys and corresponding color HEX codes as values.

palette = {"Male": "#0064FF","Female":"#FF8FDF", "Other": "#FFC300"}

Then pass it as a parameter into your pie() chart.

Would love to answer in more details but you need to provide an MRE..

0
votes

Without Plotly Express, you could try the following:

  • Stop go.Pie() from sorting your data by adding:

    sort=False
    
  • Define the colours:

    fig.update_traces(marker=dict(colors=['blue', 'red', 'green']))
    

It is not as clean as color_discrete_map though.