Plotly python 条形图堆栈顺序

Plotly python bar plot stack order

这是我的数据框代码

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

但我希望条形按值的降序排列,最大的在 start/bottom,最小的在顶部
我应该如何更新布局才能获得

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()