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

Plotly Python多子图柱状图如何实现降序排序?

解决Plotly多子图柱状图降序排序并对齐的问题

要让底部三个柱状图按降序排列且对齐,关键是统一所有子图的x轴类别顺序——单独设置categoryorder='total descending'会让每个子图基于自身柱高排序,导致各子图顺序错位。具体实现步骤如下:

  • 先确定统一的排序依据:比如选择交叉验证分数作为排序标准,将模型名称按分数从高到低排序,得到全局一致的模型列表
  • 给每个柱状图子图的x轴设置categoryorder='array',并指定categoryarray为排序好的模型列表,强制所有子图使用相同的x轴顺序
  • 确保所有柱状图子图的x轴类别范围完全一致,避免出现错位

代码示例

假设你的数据是包含模型名称、训练/测试/交叉验证分数的字典:

import plotly.graph_objects as go
from plotly.subplots import make_subplots

# 示例数据
model_data = {
    "Model": ["RandomForest", "XGBoost", "LinearRegression", "SVM"],
    "Train Score": [0.92, 0.95, 0.88, 0.90],
    "Test Score": [0.87, 0.89, 0.85, 0.86],
    "CV Score": [0.86, 0.88, 0.84, 0.85]
}

# 按交叉验证分数降序排序模型名称
sorted_models = [model for _, model in sorted(zip(model_data["CV Score"], model_data["Model"]), reverse=True)]

# 创建4个子图
fig = make_subplots(
    rows=4, cols=1,
    subplot_titles=("预测值vs真实值", "训练分数", "测试分数", "交叉验证分数")
)

# 添加直方图(示例占位,替换为你的真实预测/真实值数据)
fig.add_trace(go.Histogram(x=[1.2, 2.1, 3.3], name="预测值"), row=1, col=1)
fig.add_trace(go.Histogram(x=[1.1, 2.2, 3.1], name="真实值"), row=1, col=1)

# 添加训练分数柱状图,使用排序后的模型列表
fig.add_trace(go.Bar(
    x=sorted_models,
    y=[model_data["Train Score"][model_data["Model"].index(m)] for m in sorted_models],
    name="训练分数"
), row=2, col=1)

# 添加测试分数柱状图
fig.add_trace(go.Bar(
    x=sorted_models,
    y=[model_data["Test Score"][model_data["Model"].index(m)] for m in sorted_models],
    name="测试分数"
), row=3, col=1)

# 添加交叉验证分数柱状图
fig.add_trace(go.Bar(
    x=sorted_models,
    y=[model_data["CV Score"][model_data["Model"].index(m)] for m in sorted_models],
    name="CV分数"
), row=4, col=1)

# 统一设置所有柱状图子图的x轴排序规则
for row in [2, 3, 4]:
    fig.update_xaxes(
        categoryorder='array',
        categoryarray=sorted_models,
        row=row, col=1
    )

fig.show()

核心说明

  • categoryorder='array'会让x轴严格遵循categoryarray指定的顺序排列,这是实现统一排序的关键
  • 所有柱状图子图共用同一个sorted_models列表作为x轴类别,从根源上保证了子图之间的对齐
  • 排序依据可按需更换(比如换成测试分数),只需调整sorted_models的生成逻辑即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 18:06:19