如何在 Python 中使用 Plotly 更改组中变量的顺序?

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

我在 Python 中使用 Plotly 包并使用包中的示例数据集获得以下结果:

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()

但是,如您所见,日期的顺序是星期日、星期六、星期四和星期五,而我希望它是星期四、星期五、星期六、星期日。我正在查看文档但无济于事,因为我似乎只能更改组本身的顺序,而不是组内的变量。为了以防万一,我还附上了一小部分数据样本:

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

我最终解决了它,但我会 post 我的解决方案,以防有人想知道如何去做。基本上,在创建条形图之前进行排序:

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

随心所欲。