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

如何从Dash回调返回Plotly Choropleth地图?报错解决

问题修复方案

核心错误原因

你的回调函数声明了列表形式的Output([Output(component_id='my_bee_map', component_property='figure')]),但返回的是单个Figure对象,Dash要求返回值的结构必须和Output的结构匹配——列表/元组对应列表/元组形式的Output。

修复方法(二选一即可)

方法1:保持Output为列表,返回列表包裹的fig

修改回调函数的返回语句:

def update_graph(option_slctd):
    # ... 原有代码 ...
    fig = px.choropleth(...)
    # 返回列表包裹的fig
    return [fig]

方法2:将Output改为单个对象,直接返回fig

修改回调的Output声明,去掉外层列表:

@app.callback(
    Output(component_id='my_bee_map', component_property='figure'),  # 去掉外层[]
    [Input(component_id='slct_year', component_property='value')]
)
def update_graph(option_slctd):
    # ... 原有代码 ...
    fig = px.choropleth(...)
    # 直接返回fig
    return fig

额外优化:补全年份过滤逻辑

你的回调接收了年份选择参数option_slctd,但当前代码没有用它过滤数据,导致选择不同年份图表不会变化。假设你的states.csv包含year列,需要添加过滤代码:

dff = df.copy()
# 根据选中年份过滤数据
dff = dff[dff['year'] == option_slctd]

完整修复后的示例代码

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

app = Dash(__name__)
df = pd.read_csv("states.csv")

app.layout = html.Div([
    # 年份选择器示例
    dcc.Dropdown(
        id='slct_year',
        options=[{'label': y, 'value': y} for y in df['year'].unique()],
        value=df['year'].min()
    ),
    dcc.Graph(id='my_bee_map', figure={})
])

@app.callback(
    Output('my_bee_map', 'figure'),
    Input('slct_year', 'value')
)
def update_graph(option_slctd):
    dff = df[df['year'] == option_slctd]  # 年份过滤

    fig = px.choropleth(
        data_frame=dff,
        locationmode='USA-states',
        locations='state_code',
        scope="usa",
        color='Count',
        hover_data=['Count'],
        color_continuous_scale=px.colors.sequential.YlOrRd,
        labels={'Count': 'Count'},
        template='plotly_dark'
    )
    return fig

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

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 14:36:35