You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Plotly箱线图遵循pd.CategoricalDtype的自定义排序?

解决Plotly箱线图分类顺序不生效的问题

问题根源

你的代码里fig.update_xaxes(categoryorder='category ascending')这一行是导致顺序失效的核心原因:这个参数会强制Plotly使用自身默认的字母升序规则排列分类,完全覆盖了你通过pandas有序分类和category_orders设置的自定义顺序。

修正方案

方案1:移除冲突的x轴排序设置

直接删掉fig.update_xaxes(categoryorder='category ascending'),Plotly会自动尊重pandas有序分类的顺序,同时category_orders的设置也会生效:

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)

# 保留category_orders设置,移除冲突的update_xaxes
fig = px.box(df, x='group', y='values', 
             category_orders={'group': list(df.group.cat.categories)})
fig.show()

方案2:显式指定数组顺序(如果需要保留update_xaxes)

如果必须使用update_xaxes,可以将categoryorder设为'array',并通过categoryarray传入自定义顺序:

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')
# 显式指定数组顺序
fig.update_xaxes(categoryorder='array', categoryarray=df.group.cat.categories)
fig.show()

验证逻辑

两种方案都会让箱线图按B-C-A的顺序排列,核心是避免Plotly默认的字母排序规则覆盖自定义配置,同时确保pandas的有序分类或Plotly的categoryarray正确传递了期望的顺序。

内容的提问来源于stack exchange,提问作者Fabitosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 20:22:08