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

如何让Plotly图表加载时仅显示下拉菜单选中的low bin数据

问题:Plotly堆叠条形图初始加载不匹配下拉菜单选中项

现有数据集包含数值列value和分类列Cat、Bin:

import pandas as pd

df = pd.DataFrame(
    {
        'Cat': ['A', 'B', 'A', 'B', 'A', 'B'],
        'Bin': ['low', 'low', 'med', 'med', 'high', 'high'],
        'value': [17, 22, 12, 23, 29, 11] 
    }
)

使用Plotly Express绘制堆叠条形图并添加下拉菜单切换Bin选项后,页面首次加载时下拉菜单显示选中low,但图表展示了所有Bin的数据,需要实现初始加载时仅显示low对应的数据。原始代码如下:

import plotly.express as px

fig = px.bar(
  df,
  x='value',
  y='Cat',
  color='Bin'
)
fig.update_layout(
    showlegend=False,
    updatemenus=[
        {
            'buttons': [
                {
                    'label': t.name,
                    'method': 'restyle',
                    'args': [{'visible': [t2.name == t.name for t2 in fig.data]}],
                }
                for t in fig.data
            ],
            'x': 0.3,
            'xanchor': 'left',
            'y': 1.2,
        'yanchor': 'top',
        }
    ]
)

fig.show()

解决方案

只需在图表初始化后,手动设置初始的trace可见性,仅保留low对应的数据可见:

import plotly.express as px

fig = px.bar(
  df,
  x='value',
  y='Cat',
  color='Bin'
)

# 设置初始可见性:仅显示name为'low'的trace
for trace in fig.data:
    trace.visible = (trace.name == 'low')

fig.update_layout(
    showlegend=False,
    updatemenus=[
        {
            'buttons': [
                {
                    'label': t.name,
                    'method': 'restyle',
                    'args': [{'visible': [t2.name == t.name for t2 in fig.data]}],
                }
                for t in fig.data
            ],
            'x': 0.3,
            'xanchor': 'left',
            'y': 1.2,
        'yanchor': 'top',
        }
    ]
)

fig.show()

说明

Plotly默认会让所有trace处于可见状态,因此需要手动覆盖初始的visible属性,让仅low对应的trace显示。这样页面加载时,图表状态会和下拉菜单的默认选中项完全匹配,后续切换下拉菜单也能正常控制对应数据的显示与隐藏。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:12:22