[英]python plotly graph objects - discrete_color_map like in plotly express
我正在寻找一种使用 dict 的解决方案,例如:
colors={
"Oxygen": "#bf230f",
"Hydrogen": "#19848c",
"Carbon_Dioxide": "#d94f3d",
"Nitrogene": "#8c2d20"}
而不是以下示例中的列表 colors
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()
在 plotly 中,用“color_discrete_map =”表示这是可能的,但我必须使用 graph.objects。 感谢帮助!
您可以将字典转换为 pandas 系列并使用该系列:
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()
当然,将值包含在 pandas 结构中也是明智的:
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()
无论哪种情况,结果如下:
基于 bb1 帖子,解决方案可能是将列值与 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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.