按 CategoricalDtype 顺序对图进行排序

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

目标是按顺序可视化每个组的箱线图。团体人数为

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

预期的顺序是 B - C - A。

我相信plotly不会接管pandas数据帧的顺序,但手动设置它也没有帮助。

plotly==5.17.0

python pandas plotly-python categorical-data
1个回答
0
投票

Plotly 似乎并没有以同样的方式对待

list
Index
对象。

通过后者(由

categories
返回)可以解决问题:

fig = px.box(df, x='group', y='values', 
             category_orders={'group': cat_ordered.categories}) # <-- updated

fig.show();

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