Herveo
August 11, 2023, 5:18pm
1
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
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)
.
Herveo
August 11, 2023, 9:03pm
3
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