5

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

Max Ghenis
  • 14,783
  • 16
  • 84
  • 132
  • Does this answer your question? [Customizing the order of legends in plotly](https://stackoverflow.com/questions/56808693/customizing-the-order-of-legends-in-plotly) – vestland Jun 29 '20 at 14:55
  • 1
    @vestland 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'}`. – Max Ghenis Jul 01 '20 at 17:07

1 Answers1

10

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

Max Ghenis
  • 14,783
  • 16
  • 84
  • 132