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

Plotly Dash choropleth地图回调不更新问题求助

问题:Plotly Dash中Choropleth地图无法随滑块年份更新

在使用Plotly Dash的回调函数时,希望choropleth地图能随滑块选择的年份更新。滑块本身功能正常,已通过print语句确认筛选出的数据正确,但地图并未随之更新。

错误原因

你的代码中创建choropleth图表时,错误地使用了原始数据集df来指定locations和color参数,而非筛选后的filtered_df。这导致图表始终加载全量数据,不会随选中的年份变化。

修正后的代码

app = dash.Dash(__name__, external_stylesheets=[dbc.themes.FLATLY])

app.layout = dbc.Container(html.Div([

    dbc.Row(
        [
            dcc.Graph(id='graph-with-slider'),
            dcc.Slider(
                min=df['year'].min(),
                max=df['year'].max(),
                step=None,
                value=df['year'].max(),
                marks={str(year): str(year) for year in df['year'].unique()},
                id='year-slider'
            )
        ]
    )
]))


@app.callback(
    Output(component_id='graph-with-slider', component_property='figure'),
    [Input(component_id='year-slider', component_property='value')]
)
def update_figure(selected_year):
    filtered_df = df.loc[df.year == selected_year].reset_index()
    #print(filtered_df)

    # 关键修改:将df替换为filtered_df
    fig = px.choropleth(filtered_df, locations=filtered_df['Country Code'], locationmode='ISO-3',
                        color=filtered_df['life_expectancy_total'], color_continuous_scale=colorscale)
    fig.update_layout(transition_duration=500)
    return fig

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

关键说明

  • 回调函数中生成图表时,所有数据相关的字段(locations、color等)必须引用筛选后的filtered_df,确保图表使用当前选中年份的数据。
  • 保持transition_duration设置可以让地图更新时有平滑过渡效果。

内容的提问来源于stack exchange,提问作者Kathrin-1992

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 03:20:15