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

如何在Python Dash中实现多过滤器联动筛选图表

Dash多过滤器联动实现方案(地区+性别)

要实现两个过滤器(地区Filtro1、性别Filtro2)的联动筛选,让两个筛选条件共同作用于所有图表,只需修改回调逻辑,同时监听两个过滤器的输入并组合筛选规则即可。以下是完整的修改后代码:

from dash import Dash, html, dcc, Input, Output
import plotly.express as px
import dash_bootstrap_components as dbc
import pandas as pd
import numpy as np

external_stylesheets = [dbc.themes.CERULEAN]

app = Dash(__name__, external_stylesheets=external_stylesheets)

# 替换为你本地的数据集路径
df = pd.read_csv("C:\\Users\\lucas\\Downloads\\insurance.csv")

# 初始化图表(仅首次加载用)
fig = px.bar(df, x="age", y="bmi", color="region", barmode="group")
fig2 = px.scatter(df, x="bmi", y="charges", color="smoker")
fig3 = px.histogram(df, x="age", y="bmi", color="sex", marginal="rug", hover_data=df.columns)

# 生成过滤器选项
filtro = df.region.unique()
filtro = np.append(filtro, "Regiões")

filtro2 = df.sex.unique()
filtro2 = np.append(filtro2, "Sexo")

app.layout = html.Div(children=[
    html.Div([    
        html.Div([
            html.H1(children='Gráfico de Barras'),
            html.Div(children='BMI x Idade'),
            dcc.Dropdown(filtro, value="Regiões", id="Filtro1"),
            dcc.Graph(id='graph1', figure=fig),  
        ], className='col-md-6'),
        html.Div([
            html.H1(children='Regressão'),
            html.Div(children='Relação entre fumantes e os planos de saúde mais caros'),
            dcc.Dropdown(filtro2, value="Sexo", id="Filtro2"),
            dcc.Graph(id='graph2', figure=fig2),  
        ], className='col-md-6'),
    ], className='row'),
    html.Div([
        html.H1(children='Histograma'),
        html.Div(children='Histograma com dados da figura 1'),
        dcc.Graph(id='graph3', figure=fig3),  
    ]),
])

@app.callback(
    Output('graph1','figure'),
    Output('graph2','figure'),
    Output('graph3','figure'),
    Input('Filtro1','value'),
    Input('Filtro2','value'),  # 添加第二个过滤器作为输入
)
def update_output(selected_region, selected_sex):
    # 初始化筛选数据集为全量数据
    filtered_df = df.copy()
    
    # 应用地区筛选规则
    if selected_region != "Regiões":
        filtered_df = filtered_df[filtered_df['region'] == selected_region]
    
    # 应用性别筛选规则(与地区筛选逻辑联动)
    if selected_sex != "Sexo":
        filtered_df = filtered_df[filtered_df['sex'] == selected_sex]
    
    # 基于筛选后的数据集重新生成所有图表
    fig = px.bar(filtered_df, x="age", y="bmi", color="region", barmode="group")
    fig2 = px.scatter(filtered_df, x="bmi", y="charges", color="smoker")
    fig3 = px.histogram(filtered_df, x="age", y="bmi", color="sex", marginal="rug", hover_data=df.columns)
    
    return fig, fig2, fig3

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

关键修改说明

  1. 扩展回调输入:在@app.callback中添加Input('Filtro2','value'),让回调同时监听两个过滤器的变化
  2. 组合筛选逻辑:以全量数据集为基础,依次应用地区和性别筛选规则,确保两个条件同时生效(逻辑与)
  3. 简化代码结构:用逐步过滤替代嵌套if-else,让筛选逻辑更清晰易维护

内容的提问来源于stack exchange,提问作者Lucas Brecht Fernandes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 17:20:57