目标是按顺序可视化每个组的箱线图。团体人数为
pd.CategoricalDtype
并已订购。
我没能设法遵守命令。相反,它仅按字母顺序排序。
import pandas as pd
import numpy as np
import plotly.express as px
df = pd.DataFrame({'group': list('CAACCBAA'), 'values': np.random.random(8)})
cat_ordered = pd.CategoricalDtype(categories=['B', 'C', 'A'], ordered=True)
df['group'] = df['group'].astype(cat_ordered)
fig = px.box(df, x='group', y='values',
category_orders={'group': list(df.group.cat.categories)})
fig.update_xaxes(categoryorder='category ascending')
fig.show()
我相信plotly不会接管pandas数据帧的顺序,但手动设置它也没有帮助。
plotly==5.17.0
Plotly 似乎并没有以同样的方式对待
list
和 Index
对象。
categories
返回)可以解决问题:
fig = px.box(df, x='group', y='values',
category_orders={'group': cat_ordered.categories}) # <-- updated
fig.show();