From PX to GO : from color_discrete_sequence to marker_colors

Hi there,

Here is an example of a Pie Chart realized with PX from this page :

https://plotly.com/python/pie-charts/

import plotly.express as px
df = px.data.tips()
fig = px.pie(df, values='tip', names='day', color_discrete_sequence=px.colors.sequential.RdBu)
fig.show()

And I wanted to switch from PX to GO. But I got a problem with colors if I simply do this :

import plotly.graph_objects as go
df = px.data.tips()
fig = go.Figure(data=[go.Pie(
    labels=df['day'],
    values=df['tip'],
    marker_colors=px.colors.sequential.RdBu
)])
fig.show()

I can easily fix this problem by manipulating the dataframe before creating the figure.

But I was wondering whether or not I could change something directly on the figure object (instead of the dataframe) ?

Thanks in advance,

Herve

hi @Herveo
:wave: welcome to the community.

I was able to do it by mapping the colors you wish for each day to the dataframe.

import plotly.graph_objects as go
import plotly.express as px
df = px.data.tips()

colors = {'Sat':'red','Sun':'blue','Thur':'pink', 'Fri':'rgb(124, 103, 37)'}
df['day_colors'] = df['day'].apply(lambda x: colors[x])

fig = go.Figure(data=[go.Pie(
    labels=df['day'],
    values=df['tip'],
    marker_colors=df['day_colors']
)])
fig.show()

I don’t think there’s a way to do it directly in GO, unless you have pre-determined list of colors, whose length is the same as the len(df).

Hi @adamschroeder

Thanks for your answer.

Yes it works with a mapping. Using β€˜px.colors.sequential.RdBu’, it could be something like this:

colors = {
    'Sat': px.colors.sequential.RdBu[0],
    'Sun': px.colors.sequential.RdBu[1],
    'Thur': px.colors.sequential.RdBu[2],
    'Fri': px.colors.sequential.RdBu[3]
    }

And another way could be first to group the dataframe by β€˜day’ (+ a sum()). And so after we can simply have the same value for the color parameter (just like with PX) :

marker_colors=px.colors.sequential.RdBu

But no way to handle this directly in GO…

Thanks

1 Like