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

如何同时按值排序条形图并强制指定图例顺序?

解决方案

问题根源

你之前的方案中,categoryarray固定了x轴的所有国家类别,即使隐藏某个大洲的trace,x轴仍会保留全部类别,导致空白区域。改用单trace+颜色分组的方式,结合有序类别控制图例顺序,就能同时满足所有需求。

修正代码

import plotly.graph_objects as go
import pandas as pd

# 原始数据
df = pd.DataFrame({
    'Continent': ['Europe', 'Africa', 'Asia', 'Europe', 'Africa'],
    'Country': ['Poland', 'Egypt', 'China', 'France', 'South Africa'],
    'Value': [0.5, 0.2, 0.3, 0.1, 0.8]
})

# 1. 设置大洲的有序类别,强制图例显示顺序为Asia、Europe、Africa
df['Continent'] = pd.Categorical(df['Continent'], categories=['Asia', 'Europe', 'Africa'], ordered=True)

# 2. 按Value列降序排序,确保条形顺序符合要求
df_sorted = df.sort_values(by='Value', ascending=False)

# 3. 创建单trace,用颜色自动区分大洲
fig = go.Figure(go.Bar(
    x=df_sorted['Country'],
    y=df_sorted['Value'],
    color=df_sorted['Continent'],
    # 可选:自定义大洲颜色
    marker_color={
        'Asia': '#1f77b4',
        'Europe': '#ff7f0e',
        'Africa': '#2ca02c'
    }
))

# 4. 优化图例交互:点击图例组时隐藏对应所有条形
fig.update_layout(
    legend={
        'groupclick': 'toggleitem',
        'itemsizing': 'constant'
    },
    # 确保x轴严格按排序后的国家顺序显示
    xaxis={'categoryorder': 'array', 'categoryarray': df_sorted['Country']}
)

fig.show()

核心改进

  • 自动处理x轴缩放:用color参数分组后,隐藏某个大洲时,对应国家的条形会被完全移除,x轴会自动收缩,不会留下空白。
  • 精准控制图例顺序:通过pd.Categorical设置大洲的有序类别,plotly会自动按该顺序生成图例。
  • 简化代码结构:无需手动拆分数据分组,减少冗余代码。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 07:13:09