0
votes

i am looking for a solution to use a dict like :

colors={
    "Oxygen": "#bf230f",
    "Hydrogen": "#19848c",
    "Carbon_Dioxide": "#d94f3d",
    "Nitrogene": "#8c2d20"}

instead of the list colors in the following example

import plotly.graph_objects as go
colors = ['gold', 'mediumturquoise', 'darkorange', 'lightgreen']

fig = go.Figure(data=[go.Pie(labels=['Oxygen','Hydrogen','Carbon_Dioxide','Nitrogen'],
                             values=[4500,2500,1053,500])])
fig.update_traces(hoverinfo='label+percent', textinfo='value', textfont_size=20,
                  marker=dict(colors=colors, line=dict(color='#000000', width=2)))
fig.show()

in plotly express this is possible with "color_discrete_map=", but i have to use graph.objects. thanks for help!

2

2 Answers

0
votes

You could convert the dictionary into a pandas series and use the series:

import plotly.graph_objects as go
import pandas as pd

colors = {
    "Oxygen": "#bf230f",
    "Hydrogen": "#19848c",
    "Carbon_Dioxide": "#d94f3d",
    "Nitrogene": "#8c2d20"
}

s = pd.Series(colors)

fig = go.Figure(data=[go.Pie(labels=s.index, values=[4500, 2500, 1053, 500])])
fig.update_traces(hoverinfo='label+percent',
                  textinfo='value',
                  textfont_size=20,
                  marker=dict(colors=s, line=dict(color='#000000', width=2)))
fig.show()

Of course, then it is sensible to include the values in a pandas structure as well:

import plotly.graph_objects as go
import pandas as pd

colors = {
    "Oxygen": "#bf230f",
    "Hydrogen": "#19848c",
    "Carbon_Dioxide": "#d94f3d",
    "Nitrogene": "#8c2d20"
}

df = pd.DataFrame([colors], index=["colors"]).T
df["values"] = [4500, 2500, 1053, 500]

fig = go.Figure(data=[go.Pie(labels=df.index, values=df["values"])])
fig.update_traces(hoverinfo='label+percent',
                  textinfo='value',
                  textfont_size=20,
                  marker=dict(colors=df["colors"],
                              line=dict(color='#000000', width=2)))
fig.show()

In either case, the result is as follows:

pie chart

0
votes

based on bb1 post, the solution could be to merge the column value with the color already in the dataframe.

import plotly.express as px
import pandas as pd
colors = {
    "Oxygen": "#bf230f",
    "Hydrogen": '##8c2d20',
    "Carbon_Dioxide": "#d94f3d",
    "Nitrogene": "#8c2d20"
}

df = pd.DataFrame()
df["values"] = [4500, 2500, 1053, 500]
df['Kategorie_B'] = ['Oxygen', 'Hydrogen', 'Carbon_Dioxide', 'Nitrogene']

df["Color"] = df["Kategorie_B"].apply(lambda x: colors.get(x)) #to connect Column value to Color in Dict

fig = go.Figure(data=[go.Pie(labels=df.index, values=df["values"])])
fig.update_traces(hoverinfo='label+percent',
                  textinfo='value',
                  textfont_size=20,
                  marker=dict(colors=df["colors"],
                              line=dict(color='#000000', width=2)))
plotly.io.write_image(fig, file='pie.png', format='png')