Search code examples
pythonplotplotlyplotly-pythonplotly-express

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


Solution

  • 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