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
相关产品推荐
相关产品推荐

