【问题标题】:Plotly: How to define colors by variable/labels in plotly.graph_objects (Pie & Bar)Plotly:如何通过 plotly.graph_objects(饼图和条形图)中的变量/标签定义颜色
【发布时间】:2021-04-07 23:10:49
【问题描述】:

我是 plotly 的新手,我在下面有两个不同的图(go.Pie 和 go.Bar),我喜欢为每种类型(a:g)标签分配一种颜色,如 color_discrete_map 所示。如何将它们包含在 go.pie 和 go.bar 的代码中?谢谢

数据框:

    color_discrete_map = {'a':'rgb(42,9,4)', 
                              'b':'rgb(111,203,209)',
                              'c':'rgb(55,165,172),',
                              'd':'rgb(29,127,136)',
                              'e':'rgb(2,84,92)',
                              'f':'rgb(4,37,42)'}
    
    unit_mix_pie.add_trace(go.Pie(labels=df.index, values=df['type']), row=1, col=1)


unit_mix_bar.add_trace(go.Bar(x=df.index, y=round(df['type'],0), marker=dict(
        color=px.colors.qualitative.Pastel2, color_discrete_map=color_discrete_map,
        line=dict(color='#000000', width=2)
    )), row=1, col=1)

【问题讨论】:

  • 请提供minimal reproducible example。在您的情况下,我们至少应该能够看到您的 DataFrame 的样子,以便我们可以了解您的代码的作用,但理想情况下,我们也可以看到更多的代码,包括 unit_mix_pie 对象等等
  • 嗨@DerekO,感谢您的评论。请参阅编辑后的帖子。谢谢

标签: plotly data-visualization visualization plotly-python graph-visualization


【解决方案1】:

我有点困惑 unit_mix_pieunit_mix_bar 是只有一行和一列的子图 - 您可以将这些对象中的每一个都定义为 plotly graph_object 或 plotly express figure。

如果您使用 plotly express 定义unit_mix_pie,您可以直接将您的color_discrete_map 作为参数传递:

import pandas as pd
import plotly.express as px

df = pd.DataFrame(data={'type':list('abcdefg'), 'no':[50,100,200,300,400,500,600]})

## added another color for the type 'g'
color_discrete_map = {'a':'rgb(42,9,4)', 
                          'b':'rgb(111,203,209)',
                          'c':'rgb(55,165,172)',
                          'd':'rgb(29,127,136)',
                          'e':'rgb(2,84,92)',
                          'f':'rgb(4,37,42)',
                          'g':'purple'}

unit_mix_pie = px.pie(df, values='no', names='type', color='type', color_discrete_map=color_discrete_map)
unit_mix_pie.show()

然后您可以将 unit_mix_bar 定义为 plotly graph_object 以添加条形单独使用轨迹,将它们的类型映射到它们的颜色(我借用 vestland's answer to a similar question):

import plotly.graph_objects as go

## add the bars one at a time
unit_mix_bar=go.Figure()
for t in df['type'].unique():
    dfp = df[df['type']==t]
    unit_mix_bar.add_traces(go.Bar(x=dfp['no'], y = dfp['type'], name=t,
                         marker_color=color_discrete_map[t]))
unit_mix_bar.show()

【讨论】:

  • 谢谢@Derek O,很抱歉没有让自己说清楚。你是对的,有 2 个子图,一个有 2 个 go.pie,第二个有 2 个 go.bar。我可以调整以从 go.pie 和 go.bar 更改为 px.pie 和 px.bar。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-26
  • 1970-01-01
  • 2020-02-26
  • 1970-01-01
相关资源
最近更新 更多