Mr_Robot
Mr_Robot

Reputation: 11

How to change the order of variables in a group using Plotly in Python?

I am using the Plotly package in Python and getting the following result using a sample dataset from the package:

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

bar_plot

However, as you can see the order of the dates is Sun, Sat, Thur and Fri, while I want it to be Thur, Fri, Sat, Sun. I was looking through the documentation but to no avail, as it seems I can only change the order of the groups themselves, rather than the variables within the group. I am also attaching a small sample of the data just in case:

print(df)

     total_bill   tip     sex smoker   day    time  size
0         16.99  1.01  Female     No   Sun  Dinner     2
1         10.34  1.66    Male     No   Sun  Dinner     3
2         21.01  3.50    Male     No   Sun  Dinner     3
3         23.68  3.31    Male     No   Sun  Dinner     2
4         24.59  3.61  Female     No   Sun  Dinner     4
..          ...   ...     ...    ...   ...     ...   ...
239       29.03  5.92    Male     No   Sat  Dinner     3
240       27.18  2.00  Female    Yes   Sat  Dinner     2
241       22.67  2.00    Male    Yes   Sat  Dinner     2
242       17.82  1.75    Male     No   Sat  Dinner     2
243       18.78  3.00  Female     No  Thur  Dinner     2

Upvotes: 0

Views: 1998

Answers (1)

Mr_Robot
Mr_Robot

Reputation: 11

I ended up solving it, but I will post my solution in case anyone is wondering how to do it. Basically, sort before creating the bar chart:

import numpy as np
conditions = [(df['day'] == 'Thur'), (df['day'] == 'Fri'),
              (df['day'] == 'Sat'), (df['day'] == 'Sun')]
choices = [0,1,2,3]
df['order'] = np.select(conditions, choices)
df = df.sort_values(by='order')
fig = px.bar(df, x="sex", y="total_bill", color='day', barmode='group',height=400)
fig.show()

ordered plot

as desired.

Upvotes: 1

Related Questions