[英]How to sort x-axis label and legends in python plotly express?
对 X 轴标签进行排序
我有一个 python dict,其中包含我正在使用 pandas 数据框以宽格式展平和排序的 dicts 列表。 我希望在图中看到的是 x 轴标签要根据年份和期间进行分组和排序。 这里的时间段可能在 1-52 之间。 但我看到的是其中一组未排序(或未完全排序)。 我尝试更新categoryorder
doc 。 它似乎不像我预期的那样工作。 这是我希望在 x 轴标签上看到其中一个组的顺序:
T311-PM2:2019-8, T311-PM2:2019-11, T311-PM2:2019-12, T311-PM2:2020-3.
排序图例
传说中的类似行为也是如此。 我尝试使用legend_traceorder
doc进行排序。
我希望看到这个订单:
CS1 P, CS1-1 P, CS2 P, CS3 P, CS4 C, CS5 R, CS6 P, CS7-1 C, CS7-2 S, CS8 P
这是我将在我的代码中使用的 dict 数据:
response_dict = {
"data": [
{
"machineType": "L10-Alpha1-PM4",
"date": "2021-1",
"event": "CS3 P",
"mins": "0.00"
},
{
"machineType": "L10-Alpha1-PM4",
"date": "2021-1",
"event": "CS7-2 S",
"mins": "7.14"
},
{
"machineType": "L10-Alpha1-PM4",
"date": "2021-1",
"event": "CS8 P",
"mins": "4.17"
},
{
"machineType": "T311-PM2",
"date": "2019-8",
"event": "CS1 P",
"mins": "21.14"
},
{
"machineType": "T311-PM2",
"date": "2019-11",
"event": "CS4 C",
"mins": "2.92"
},
{
"machineType": "T311-PM2",
"date": "2019-11",
"event": "CS5 R",
"mins": "327.88"
},
{
"machineType": "T311-PM2",
"date": "2019-12",
"event": "CS7-1 C",
"mins": "43.90"
},
{
"machineType": "T311-PM2",
"date": "2019-12",
"event": "CS6 P",
"mins": "2147.27"
},
{
"machineType": "T311-PM2",
"date": "2019-8",
"event": "CS8 P",
"mins": "0.10"
},
{
"machineType": "T311-PM2",
"date": "2020-3",
"event": "CS8 P",
"mins": "19.31"
},
{
"machineType": "T828-PM2",
"date": "2018-5",
"event": "CS1-1 P",
"mins": "11.43"
},
{
"machineType": "T828-PM2",
"date": "2018-5",
"event": "CS2 P",
"mins": "10.83"
}
]
}
我的代码
import pandas as pd
import plotly.express as px
df_normalized = pd.json_normalize(response_dict['data'])
df_normalized['Mission'] = df_normalized[['machineType', 'date']].agg(':'.join, axis=1)
df_normalized[['year', 'period']] = df_normalized['date'].str.split('-', expand=True).astype(int)
data_frame = df_normalized.sort_values(by=['year', 'period'])
figure = px.bar(data_frame, x='Mission', y='date', color='event').update_xaxes(categoryorder='category ascending')#.update_layout(legend_traceorder='normal')
figure.show()
阴谋
您朝着正确的方向前进,只需要使用category_orders
而不是categoryorder
,并使用sorted()
方法定义数据的顺序。
df_normalized = pd.json_normalize(response_dict['data'])
df_normalized['Mission'] = df_normalized[['machineType', 'date']].agg(':'.join, axis=1)
df_normalized[['year', 'period']] = df_normalized['date'].str.split('-', expand=True).astype(int)
data_frame = df_normalized.sort_values(by=['year', 'period']).reset_index(drop=True)
figure = px.bar(data_frame, x='Mission',y='date', color='event',\
category_orders={'event':sorted(data_frame.event.unique()),\
'Mission':sorted(data_frame.Mission,\
key = lambda x: pd.to_datetime(x.split(':')[1]))})
figure.show()
PS:我通常在 DataFrame 上的.sort_values()
) 之后使用.reset_index(drop=True)
,以保持索引值的正确顺序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.