0

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
2
  • Please, do not provide images of code/data. Provide them in plain text, instead. Thanks! Commented Apr 5, 2020 at 18:05
  • Done! (sorry about that) Commented Apr 5, 2020 at 18:54

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.