【问题标题】:Make Stack Bar Chart Plotly Different Colors使堆栈条形图具有不同的颜色
【发布时间】:2021-11-03 03:22:03
【问题描述】:

所以我正在创建一个堆叠的条形图。我的每个堆栈都返回相同的颜色。我希望它们有不同的颜色。在这种情况下,我不想使用 plotly express。我也不想指定颜色。我只想要各种颜色。这是我的代码:

  df2 = pd.DataFrame.from_dict({'Country': {0: 'Europe',
  1: 'America',
  2: 'Asia',
  3: 'Europe',
  4: 'America',
  5: 'Asia',
  6: 'Europe',
  7: 'America',
  8: 'Asia',
  9: 'Europe',
  10: 'America',
  11: 'Asia'},
 'Year': {0: 2014,
  1: 2014,
  2: 2014,
  3: 2015,
  4: 2015,
  5: 2015,
  6: 2016,
  7: 2016,
  8: 2016,
  9: 2017,
  10: 2017,
  11: 2017},
 'Amount': {0: 1600,
  1: 410,
  2: 150,
  3: 1300,
  4: 300,
  5: 170,
  6: 1000,
  7: 500,
  8: 200,
  9: 900,
  10: 500,
  11: 210}})

fig = go.Figure()
fig.add_trace(go.Bar(x=df2['Year'], y=df['Amount'], 
                        ))
fig.update_layout(title="Personnel at Work",
                 barmode='stack')
fig.show()

【问题讨论】:

  • 您在模仿我回答的代码并提出下一个问题,但我要求您在提出下一个问题之前接受或评论我的答案中任何不可接受的方面。

标签: python pandas bar-chart plotly-python


【解决方案1】:

要使用图形对象创建堆叠图形,可以将图形指定为堆叠单元。

import pandas as pd
import plotly.graph_objects as go

fig = go.Figure()

x = [str(x) for x in df2['Year'].unique().tolist()]

for c in df2['Country'].unique():
    df3 = df2.query('Country == @c')
    fig.add_trace(go.Bar(x=x, y=df3['Amount'], name=c))
fig.update_layout(title="Personnel at Work", barmode='stack')
fig.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-25
    相关资源
    最近更新 更多