在 Plotly Express 条形图中,保持条形顺序不变的情况下反转图例顺序

5

我想要更改 plotly.express 条形图图例中项目的顺序。 例如,我想在此图表中将晚餐显示在午餐之前(当前的行为尤其在水平条形图中很尴尬,因为条形的顺序与图例的顺序相反):

import plotly.express as px
df = px.data.tips()
# Sort to put dinner on top.
df.sort_values('time', ascending=False, inplace=True)
fig = px.bar(df, y='sex', x='total_bill', color='time', barmode='group',
             orientation='h')
fig.update_layout(yaxis={'categoryorder': 'total ascending'})
fig.show()

plot result


这个回答是否解决了您的问题?自定义Plotly图例顺序 - vestland
1
@vestland 我不这么认为,它没有使用 plotly.express,虽然提到了 traceorder,但它并没有提供我所提供的简单答案,即 legend={'traceorder': 'reversed'} - Max Ghenis
1个回答

10
update_layout语句中添加 legend={'traceorder': 'reversed'}
import plotly.express as px
df = px.data.tips()
# Sort to put dinner on top.
df.sort_values('time', ascending=False, inplace=True)
fig = px.bar(df, y='sex', x='total_bill', color='time', barmode='group',
             orientation='h')
fig.update_layout(yaxis={'categoryorder': 'total ascending'},
                  legend={'traceorder': 'reversed'})
fig.show()

result of plot


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接