Reverse legend order without changing bar order in plotly express bar plot
Asked Answered
F

1

6

I'd like to change the order of the items in the legend of a plotly.express bar plot. For example, I'd like to show Dinner before Lunch on this plot (the current behavior is especially awkward with horizontal bar plots, since the order of the bars is the opposite of the legend order):

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

Ferriage answered 27/6, 2020 at 14:31 Comment(2)
Does this answer your question? Customizing the order of legends in plotlyThayer
@Thayer I don't think so, it's not using plotly.express and while it mentions traceorder it doesn't suggest the simple answer I provided, legend={'traceorder': 'reversed'}.Ferriage
F
13

Add legend={'traceorder': 'reversed'} to the update_layout statement:

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

Ferriage answered 27/6, 2020 at 14:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.