【问题标题】:Plotly python bar plot stack orderPlotly python条形图堆栈顺序
【发布时间】:2021-07-13 20:10:30
【问题描述】:

这是我的数据框代码

df = pd.DataFrame({'var_1':['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], 
                   'var_2':['m', 'n', 'o', 'm', 'n', 'o', 'm', 'n', 'o'], 
                   'var_3':[np.random.randint(25, 33) for _ in range(9)]})

这是我拥有的数据框

var_1   var_2   var_3
0   a   m   27
1   a   n   28
2   a   o   28
3   b   m   31
4   b   n   30
5   b   o   25
6   c   m   27
7   c   n   32
8   c   o   27

这是我用来获取堆积条形图的代码

fig = px.bar(df, x='var_3', y='var_1', color='var_2', orientation='h', text='var_3')
fig.update_traces(textposition='inside', insidetextanchor='middle')
fig

但我希望条形按值的降序堆叠,在开始/底部最大,在顶部最小
我应该如何更新布局以获得它

【问题讨论】:

  • 澄清一下,你想要最大的 var_3 在底部? (而且您还打算用颜色来区分单独的实体?)所以对于任何特定的 var_1,底部将是 m + n + 0 中的最大值?
  • 我不希望 m-n-o 按顺序排列。哪个最大,应该在开头如果m最大,那么它应该在开头,然后是第二大,然后是堆叠顺序的第三个

标签: python plotly data-visualization plotly-python


【解决方案1】:
df = pd.DataFrame({'var_1':['a', 'a', 'a', 'b', 'b', 'b', 'c', 'c', 'c'], 
                   'var_2':['m', 'n', 'o', 'm', 'n', 'o', 'm', 'n', 'o'], 
                   'var_3':[np.random.randint(25, 33) for _ in range(9)]})

df.sort_values(['var_1', 'var_3'], ignore_index=True, inplace=True, ascending=False)

# colors
colors = {'o': 'red',
          'm': 'blue',
          'n': 'green'}

# traces
data = []

# loop across the different rows
for i in range(df.shape[0]):
        data.append(go.Bar(x=[df['var_3'][i]],
                           y=[df['var_1'][i]],
                           orientation='h',
                           text=str(df['var_3'][i]),
                           marker=dict(color=colors[df['var_2'][i]]),
                           name=df['var_2'][i],
                           legendgroup=df['var_2'][i],
                           showlegend=(i in [1, 2, 3])))
        
# layout
layout = dict(barmode='stack', 
              yaxis={'title': 'var_1'},
              xaxis={'title': 'var_3'})

# figure
fig = go.Figure(data=data, layout=layout)    
fig.update_traces(textposition='inside', insidetextanchor='middle')
fig.show()

【讨论】:

  • 是的 - 我在想数据必须被展平,还没有找到内置的解决方法。
猜你喜欢
  • 1970-01-01
  • 2016-04-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-08
相关资源
最近更新 更多