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

基于分类列创建Plotly下拉筛选按钮实现图表动态更新

解决方案:实现按分类切换的双Y轴折线图

我来帮你解决这个下拉按钮失效的问题!你的原始代码主要有两个核心问题:一是没有针对分类筛选对应的数据,只是错误设置了trace的可见性;二是下拉按钮的逻辑混乱,导致点击后无法正确更新图表内容。下面是修正后的完整方案,完美实现你需要的功能:

import pandas as pd
from plotly.offline import init_notebook_mode, iplot
import plotly.graph_objs as go

init_notebook_mode(connected=True)

# 初始化你的DataFrame
df = pd.DataFrame()
df['category'] = ['G1', 'G1', 'G1', 'G1','G1', 'G1','G1', 'G2', 'G2', 'G2', 'G2', 'G2', 'G2', 'G2']
df['date'] = ['2012-04-01', '2012-04-05', '2012-04-09', '2012-04-11', '2012-04-16', '2012-04-23', '2012-04-30', '2012-04-01', '2012-04-05', '2012-04-09', '2012-04-11', '2012-04-16', '2012-04-23', '2012-04-30']
df['col1'] = [54, 34, 65, 67, 23, 34, 54, 23, 67, 24, 64, 24, 45, 89]
df['col2'] = round(df['col1'] * 0.85)

# 页面加载时默认显示第一个分类(G1)的数据
default_cat = df['category'].unique()[0]
df_default = df[df['category'] == default_cat]

# 创建初始的两个折线trace,col2绑定到右侧Y轴
trace1 = go.Scatter(
    x=df_default['date'],
    y=df_default['col1'],
    mode='lines',
    name='col1',
    marker={'color': 'blue'}
)
trace2 = go.Scatter(
    x=df_default['date'],
    y=df_default['col2'],
    mode='lines',
    name='col2',
    marker={'color': 'yellow'},
    yaxis='y2'  # 把col2指定到第二个Y轴
)

data = [trace1, trace2]

# 配置布局,包含双Y轴和下拉菜单容器
layout = go.Layout(
    title='Category-wise Dual Y-axis Line Chart',
    xaxis=dict(
        title='Date',
        type='date',
        tickformat='%Y-%m-%d',
        titlefont=dict(family='Old Standard TT, serif', size=20, color='black')
    ),
    yaxis=dict(
        title='col1 Values',
        titlefont=dict(family='Old Standard TT, serif', size=20, color='blue')
    ),
    yaxis2=dict(
        title='col2 Values',
        titlefont=dict(family='Old Standard TT, serif', size=20, color='yellow'),
        overlaying='y',  # 与左侧Y轴重叠
        side='right'  # 显示在右侧
    ),
    updatemenus=[dict(
        buttons=[],
        direction='down',
        showactive=True,
        x=0.1,
        xanchor='left',
        y=1.15,
        yanchor='top'
    )]
)

# 为每个分类生成对应的下拉按钮
for cat in df['category'].unique():
    df_filtered = df[df['category'] == cat]
    # 定义点击按钮时要更新的trace数据
    updated_traces = [
        go.Scatter(
            x=df_filtered['date'],
            y=df_filtered['col1'],
            mode='lines',
            name='col1',
            marker={'color': 'blue'}
        ),
        go.Scatter(
            x=df_filtered['date'],
            y=df_filtered['col2'],
            mode='lines',
            name='col2',
            marker={'color': 'yellow'},
            yaxis='y2'
        )
    ]
    # 添加按钮到下拉菜单
    layout['updatemenus'][0]['buttons'].append(
        dict(
            label=cat,
            method='restyle',
            args=[updated_traces]
        )
    )

fig = go.Figure(data=data, layout=layout)
iplot(fig)

关键修改说明

  • 双Y轴配置:新增了右侧Y轴,让col1和col2的数据分别显示在左右两侧,避免数值重叠难以区分。
  • 动态数据更新:每个下拉按钮点击时,通过restyle方法直接替换两个trace的x、y数据为对应分类的筛选结果,而不是简单切换可见性,逻辑更直观可靠。
  • 默认数据初始化:页面加载时自动显示第一个分类的数据,提升初始体验。
  • 简化按钮逻辑:去掉了复杂的可见性数组计算,直接为每个分类生成对应的数据trace,代码可读性更强。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 08:27:15