Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse legend order without changing bar order in plotly express bar plot

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

like image 766
Max Ghenis Avatar asked Sep 02 '26 23:09

Max Ghenis


1 Answers

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

like image 52
Max Ghenis Avatar answered Sep 04 '26 13:09

Max Ghenis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!