使用Python中的Plotly更改组中变量的顺序

问题描述 投票:0回答:1

我正在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
python plotly visualization
1个回答
0
投票

我最终解决了这个问题,但是如果有人想知道如何解决,我会发布我的解决方案。基本上,在创建条形图之前进行排序:

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

根据需要。

© www.soinside.com 2019 - 2024. All rights reserved.