Changing the within-group order of a grouped bar plot in plotly

Viewed 1611

I'd like to change the order of my within-group variable in a plotly bar plot in Python. For example, how can I switch the order of lunch and dinner here?

import plotly.express as px
df = px.data.tips()
fig = px.bar(df, x='sex', y='total_bill', color='time', barmode='group')
fig.show()

enter image description here

categoryorder can only change the order of groups, i.e. Male and Female.

1 Answers

Sort the df in descending order basis the column time.

import plotly.express as px
df = px.data.tips()
df.sort_values(['time'],ascending=[False],inplace=True)
fig = px.bar(df, x='sex', y='total_bill', color='time', barmode='group')
fig.show()

OUTPUT: enter image description here

Related