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

Plotly Dash中实现柱状图与饼图图例双向联动需求

Dash中Plotly柱状图与饼图双向图例联动解决方案

核心逻辑

通过监听两个图表的restyleData属性(图例点击会触发该事件),获取当前可见的系列类别,据此过滤原始数据并更新另一个图表,实现双向联动。

完整实现代码

import dash
from dash import dcc, html, Input, Output, callback
import plotly.express as px
import pandas as pd

# 模拟示例数据
df = pd.DataFrame({
    'Lead_Time': ['0-2 days', '2-4 days', '4-6 days', '6+ days'] * 4,
    'Status': ['Duplicate', 'Qualified', 'Duplicate', 'Qualified'] * 4,
    'Count': [15, 22, 10, 18, 8, 14, 5, 12, 20, 25, 12, 16, 5, 10, 3, 8]
})

app = dash.Dash(__name__)

app.layout = html.Div([
    html.Div([
        dcc.Graph(id='bar-chart', figure=px.bar(df, x='Lead_Time', y='Count', color='Status', barmode='group'))
    ], style={'width': '48%', 'display': 'inline-block'}),
    html.Div([
        dcc.Graph(id='pie-chart', figure=px.pie(df, values='Count', names='Lead_Time'))
    ], style={'width': '48%', 'display': 'inline-block'})
])

@callback(
    [Output('bar-chart', 'figure'), Output('pie-chart', 'figure')],
    [Input('bar-chart', 'restyleData'), Input('pie-chart', 'restyleData')],
    prevent_initial_call=False
)
def update_charts(bar_restyle, pie_restyle):
    filtered_df = df.copy()
    
    # 处理柱状图图例点击(过滤Status类别)
    if bar_restyle is not None:
        status_cats = df['Status'].unique()
        visible_status = [status_cats[i] for i, val in enumerate(bar_restyle[0]['visible']) if val]
        filtered_df = filtered_df[filtered_df['Status'].isin(visible_status)]
    
    # 处理饼图图例点击(过滤Lead_Time类别)
    if pie_restyle is not None:
        leadtime_cats = df['Lead_Time'].unique()
        visible_leadtime = [leadtime_cats[i] for i, val in enumerate(pie_restyle[0]['visible']) if val]
        filtered_df = filtered_df[filtered_df['Lead_Time'].isin(visible_leadtime)]
    
    # 生成更新后的图表
    bar_fig = px.bar(filtered_df, x='Lead_Time', y='Count', color='Status', barmode='group')
    pie_fig = px.pie(filtered_df, values='Count', names='Lead_Time')
    
    return bar_fig, pie_fig

if __name__ == '__main__':
    app.run_server(debug=True)

关键细节说明

  • restyleData:图例点击时,该属性会返回包含visible列表的字典,列表中每个元素对应系列是否可见。
  • 双向过滤逻辑:先判断哪个图表的图例被点击,再根据可见状态筛选对应的数据类别,最后用过滤后的数据重新渲染两个图表。
  • 初始状态处理:设置prevent_initial_call=False,确保页面加载时默认渲染全量数据的图表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 14:50:14