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

如何为Plotly图表中的世界银行收入组设置自定义排序

调整Plotly中世界银行收入分组的轴排序顺序

方法1:通过Pandas设置有序类别(推荐)

直接将World bank income group列转为有序类别类型,让Plotly自动沿用这个逻辑顺序,后续所有基于该列的可视化都会统一遵循这个排序,不需要重复设置。

完整代码示例:

import pandas as pd
import plotly.express as px

# 定义你需要的逻辑排序
desired_order = ['Low Income', 'Lower Middle Income', 'Upper Middle Income', 'High Income']

# 将目标列转为有序类别
flat_f4['World bank income group'] = pd.Categorical(
    flat_f4['World bank income group'],
    categories=desired_order,
    ordered=True
)

# 执行原绘图代码即可
fig4 = px.histogram(flat_f4, x='World bank income group', y='Percentage', color='Age group', barmode='group')
fig4.show()

方法2:直接在Plotly布局中指定排序

如果不想修改原始数据,可以在绘图后通过update_layout手动指定x轴的类别顺序,仅对当前图表生效:

完整代码示例:

import plotly.express as px

# 原绘图代码
fig4 = px.histogram(flat_f4, x='World bank income group', y='Percentage', color='Age group', barmode='group')

# 强制设置x轴的分组顺序
fig4.update_layout(
    xaxis={
        'categoryorder': 'array',
        'categoryarray': ['Low Income', 'Lower Middle Income', 'Upper Middle Income', 'High Income']
    }
)
fig4.show()

两种方法的区别

  • 方法1从数据层面统一排序,适合需要多次使用该分组列的场景,避免重复配置;
  • 方法2仅针对当前图表调整,适合临时修改排序的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 20:06:20