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

使用Dash实现Plotly图表Y轴下拉切换时语法错误求助

问题排查结果

根因

语法错误的核心原因是你修改代码时丢失了html.Div组件的闭合语句,导致app.layout的赋值语句未正常结束,Python解析器将后续的回调装饰器、函数定义代码识别为html.Div的输入参数,最终在函数定义行触发语法错误。

你可以对比两段代码的app.layout尾部结构:

  • 可运行的基准代码中,html.Label组件结束后,额外有一行])用于闭合外层html.Div的列表和括号
  • 报错代码中删除了这部分闭合逻辑,仅闭合了html.Label就直接开始写回调相关代码

修复方案

将报错代码的app.layout部分补全闭合逻辑,修改后如下:

# Build App
app = JupyterDash(__name__)
app.layout = html.Div([
    html.H1("Index Scatterplot"),
    dcc.Graph(id='graph'),
    html.Label([
        "constituent",
        dcc.Dropdown(
            id='constituent-dropdown', clearable=False,
            value='AAPL.O', options=[
                {'label': c, 'value': c}
                for c in ['AAPL.O', 'AMZN.O', 'TSLA.O']
            ]),
    ]), # 补全html.Label后的逗号
]) # 补全html.Div的闭合语句

# Define callback to update graph
@app.callback(
    Output('graph', 'figure'),
    [Input("constituent-dropdown", "value")]
)
def update_figure(constituent):
    return px.scatter(
        data, x=".SPX", y=constituent, color="size",
        color_continuous_scale='plasma',
        render_mode="webgl", title="Return Distribution"
    )

# Run app and display result inline in the notebook
app.run_server(mode='inline', port=8050) # 替换XXXX为合法端口号,比如8050

其他注意事项

  • 原代码中的port=XXXX需要替换为合法的数字端口,比如8050,否则运行时会触发额外错误
  • 装饰器@app.callback和被装饰的函数update_figure之间不需要加空行,避免部分Python版本出现解析异常

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 18:51:03