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

Dash餐厅目录应用:Dropdown筛选正常但地图不更新问题求助

Dash地图无法随Dropdown筛选更新的解决方案

问题描述

开发Dash餐厅目录应用时,Dropdown筛选器可正常触发回调:页面容器文本能正确显示选中菜系,控制台打印的筛选后DataFrame符合预期,但scatter_mapbox地图始终显示全部餐厅,无法随选中菜系更新。

原因分析

代码中px.scatter_mapbox使用的纬度/经度列名与实际数据列名不匹配:数据中纬度列是lat、经度列是long,但代码里错误指定为Latitude和Longitude,导致Plotly无法正确读取筛选后的坐标数据,最终地图仍加载全量餐厅数据。

修复代码

修改px.scatter_mapbox的lat和lon参数,替换为数据实际的列名:

import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output

import pandas as pd
import plotly.express as px 


app = dash.Dash(__name__)  # 改为标准写法,避免命名冲突

df = pd.read_excel('Resturants.XLSX')


app.layout = html.Div([
    html.H1('Resturant map by cusine', style={'text-align': 'center'} ),

    dcc.Dropdown(id='cusine_dd', 
                 options=[{'label': i, 'value': i} for i in df.cusines.unique()],
                  value = 'Chinese',
                 style={'width':'40%'}),
    
    html.Div(id= 'output', children =[] ),

    dcc.Graph(id='mapbycusine', figure={})
])

@app.callback(
    [Output(component_id='output', component_property='children'),
    Output(component_id='mapbycusine', component_property='figure')],
    [Input(component_id='cusine_dd', component_property='value')]
)
def update_figure(input_cusine):
    container = f"Currently showing {input_cusine}"
    df_copy = df.copy(deep=True)
    if input_cusine:
        df_copy = df_copy[df_copy['cusines'] == input_cusine]  
    print(df_copy.head())
    # 修正lat和lon为数据实际列名
    fig = px.scatter_mapbox(data_frame=df_copy, lat='lat',  lon='long', zoom=3, height=300, hover_data= ['cusines'])
    fig.update_layout(mapbox_style="open-street-map")
    fig.update_layout(height=1000, margin={"r":100,"t":100,"l":100,"b":300})
    return container, fig

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

额外建议

  • 将app = dash.Dash('app')改为app = dash.Dash(__name__),这是Dash应用的标准初始化方式,可避免潜在的资源加载问题。
  • 若数据中cusines列存在多菜系(如逗号分隔的多个标签),可改用模糊匹配逻辑:df_copy[df_copy['cusines'].str.contains(input_cusine)],提升筛选灵活性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 18:31:09