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

Dash回调更新Plotly Figure遇IncorrectTypeException错误求助

问题:Plotly Dash回调触发IncorrectTypeException错误

编写了一段用Plotly展示直方图的代码,希望通过RangeSlider更新图表,仅显示用户指定的年份范围。按照回调更新图表的标准模板编写后,触发了以下错误:

IncorrectTypeException: component_id must be a string or dict, found Figure

使用的是可正常显示的Plotly figure,也将源DataFrame的类型从'object'改为'string',但问题仍未解决。想了解错误原因、解决思路,以及component_id的含义。

附上代码:

fig = px.histogram(df, y = 'Procedure', color = 'LOE')
app = JupyterDash(__name__)
app.layout = html.Div([
   dcc.Graph(figure=fig),
   dcc.RangeSlider(min = 2000, max = 2020, value = [2000,2020], step = 1,
                   marks={i: str(i) for i in range(2000,2020,1)}, id = 'range-slider')
])

@app.callback(
Output(fig, 'data'),
Input('range-slider', 'value'),
)
def update_table(slider_value):
   if not slider_value:
       return dash.no_update
   new_df = #modify df here
   return px.histogram(new_df, y = 'Procedure', color = 'LOE')

if __name__ == '__main__'
   app.run_server(mode = 'inline')

解决方法

1. 核心错误:component_id的含义与Output参数误用

component_id是Dash组件的唯一标识字符串,回调的Output必须指定组件id和该组件的属性名,而非直接传入Plotly Figure对象。你的代码直接将fig传给Output,这就是错误的根源。

修正步骤:

  • 给dcc.Graph添加唯一id,比如id='histogram-graph'
  • 将回调的Output改为Output('histogram-graph', 'figure')——我们要更新的是Graph组件的figure属性,而非data属性

2. 回调返回值匹配属性类型

因为Output指定的是figure属性,所以回调函数需要返回完整的Plotly Figure对象,你的返回逻辑本身没问题,但要补充正确的年份过滤逻辑(根据slider_value筛选数据)。

3. 修复语法错误

if __name__ == '__main__'语句末尾缺少冒号:,这会导致代码无法正常运行。

修正后的完整代码

import plotly.express as px
from jupyter_dash import JupyterDash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output

# 假设df已提前定义并加载数据
fig = px.histogram(df, y='Procedure', color='LOE')
app = JupyterDash(__name__)
app.layout = html.Div([
    dcc.Graph(figure=fig, id='histogram-graph'),  # 为Graph添加id
    dcc.RangeSlider(
        min=2000, 
        max=2020, 
        value=[2000, 2020], 
        step=1,
        marks={i: str(i) for i in range(2000, 2021, 1)},  # 修正marks范围,包含2020
        id='range-slider'
    )
])

@app.callback(
    Output('histogram-graph', 'figure'),  # 改为组件id+目标属性名
    Input('range-slider', 'value'),
)
def update_histogram(slider_value):
    if not slider_value:
        return dash.no_update
    # 补充年份过滤逻辑(假设df存在名为'Year'的年份列)
    new_df = df[(df['Year'] >= slider_value[0]) & (df['Year'] <= slider_value[1])]
    return px.histogram(new_df, y='Procedure', color='LOE')

if __name__ == '__main__':  # 添加缺失的冒号
    app.run_server(mode='inline')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 07:00:57