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

Plotly Dash中Dropdown、Graph与RangeSlider交互失效问题求助

问题原因与解决方法

问题根源

你的回调函数仅对年份范围进行了数据过滤,完全没有使用下拉框传入的sel_country参数筛选国家,所以下拉框的选择无法影响图表内容。

修正后的回调代码

@app.callback(
    Output('the_graph', 'figure'),
    [Input('the_year', 'value'),
    Input('the_country', 'value')]
)
def update_graph(sel_year, sel_country):
    # 同时应用年份范围和选中国家的过滤条件
    dff = data[
        (data['year'] >= sel_year[0]) & 
        (data['year'] <= sel_year[1]) & 
        (data['country'].isin(sel_country))
    ]
    graph = px.line(
        dff,
        x='year',  # 直接传入列名即可,无需dff['year']
        y='pop',
        color='country',
        markers=True,
    )
    return graph

额外注意事项

  • 确保你的Dropdown组件开启了多选模式,即设置multi=True,示例代码:
dcc.Dropdown(
    id='the_country',
    options=[{'label': cntry, 'value': cntry} for cntry in sorted(data['country'].unique())],
    value=data['country'].unique()[:3],  # 默认选中3个国家,可根据需求调整
    multi=True
)
  • 若允许用户不选择任何国家,可在回调中添加空值判断,避免报错:
def update_graph(sel_year, sel_country):
    # 处理未选中任何国家的情况
    if not sel_country:
        return px.line(title="请选择至少一个国家")
    
    dff = data[
        (data['year'] >= sel_year[0]) & 
        (data['year'] <= sel_year[1]) & 
        (data['country'].isin(sel_country))
    ]
    graph = px.line(
        dff,
        x='year',
        y='pop',
        color='country',
        markers=True,
    )
    return graph

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 08:55:18