簡體   English   中英

python plotly 圖形對象 - 類似於 plotly 中的離散顏色映射

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM