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

Dash散点图无法正常显示问题求助

Dash散点图无法正常显示问题求助

我帮你找到了问题所在!你的散点图回调函数里的返回格式写错了,这是Dash新手很容易踩的坑。

看一下你的update_allocation_history函数:你先创建了一个go.Figure()对象并添加trace,最后却把这个整个Figure对象放到了data列表里返回,这不符合Dash对figure结构的要求——Dash要求figure字典里的data字段是trace对象的列表,而不是包含Figure对象的列表。

这里有两种修正方法,选一种就行:

方法1:直接构建trace列表返回

@app.callback(
    Output('allocation_history_chart','figure'),
    [Input('type_filter','value')]
)
def update_allocation_history(type_):
    if type_ == 'All':
        filtered = df_index
    else:
        mask = df['Type'] == type_
        filtered = df_index.loc[mask]
    
    # 初始化一个空的trace列表
    traces = []
    for ticker in filtered.index:
        traces.append(
            go.Scatter(
                x = filtered.loc[ticker].index,
                y = filtered.loc[ticker],
                name = ticker
            )
        )
    
    return {
        'data': traces,
        'layout': go.Layout(title='History of Asset')
    }

方法2:直接返回完整的Figure对象

Plotly的Figure对象本身就可以被Dash接受,你可以直接构建好Figure后返回,不用拆成data和layout:

@app.callback(
    Output('allocation_history_chart','figure'),
    [Input('type_filter','value')]
)
def update_allocation_history(type_):
    if type_ == 'All':
        filtered = df_index
    else:
        mask = df['Type'] == type_
        filtered = df_index.loc[mask]
    
    fig = go.Figure()
    for ticker in filtered.index:
        fig.add_trace(
            go.Scatter(
                x = filtered.loc[ticker].index,
                y = filtered.loc[ticker],
                name = ticker
            )
        )
    # 直接在这里设置布局
    fig.update_layout(title='History of Asset')
    # 返回整个Figure对象即可
    return fig

另外,你可以顺便检查一下df_index的数据结构是否符合预期:比如filtered.loc[ticker]是否是一个带时间索引的序列,x轴的日期格式是否能被Plotly正确解析——不过这不是当前不显示的主要原因,主要问题还是返回格式错误。

备注:内容来源于stack exchange,提问作者mattéo bernard

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 13:04:07