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

Plotly Dash中hoverData结合go.Table实现悬停表格报错求助

解决Plotly Dash中hoverData关联侧边表格的问题

你的问题主要有两个核心点:一是错误地尝试直接访问Graph组件的.figure属性导致报错,二是需要正确通过当前图表的figure实例获取trace名称来匹配数据源。我来一步步帮你修复:

1. 错误原因解析

你遇到的AttributeError: 'Graph' object has no attribute 'figure',是因为app.layout['plot']是Dash的Graph组件对象(布局定义的一部分),而不是运行时渲染后的实际figure数据。要获取当前图表的figure,必须通过回调的State参数来传递。

另外,你的回调Output写错了:应该是Output('hover-data', 'figure'),而不是'graph'——Dash的Graph组件接受的属性是figure,这也是悬停时无显示的潜在原因之一。

2. 修改后的完整回调代码

@app.callback(
    Output('hover-data', 'figure'),  # 修正Output目标属性为figure
    [Input('plot', 'hoverData')],
    [State('plot', 'figure')]  # 添加State获取当前图表的figure数据
) 
def hover_data(hoverData, current_figure):
    # 处理页面加载时hoverData为空的情况
    if not hoverData:
        return go.Figure(data=[go.Table(
            header=dict(values=['p_mean', 'p_median', 'range', 'std'], fill_color='paleturquoise', align='left'),
            cells=dict(values=[[], [], [], []])
        )])
    
    Die_test = hoverData['points'][0]['x']
    curve_number = hoverData['points'][0]['curveNumber']
    # 从当前figure的data中获取对应trace的name,提取纯测试名称(适配你定义的trace name格式)
    trace_name = current_figure['data'][curve_number]['name'].split(',')[0].strip()
    
    # 匹配对应的数据源df
    df = df_lists.get(trace_name)
    if not df:
        return go.Figure(data=[go.Table(
            header=dict(values=['提示'], fill_color='lightcoral', align='left'),
            cells=dict(values=['未找到对应测试数据'])
        )])
    
    df_filtered = df[df['test_name'] == Die_test]
    # 构建表格可视化figure
    table_data = [go.Table(
        header=dict(values=['p_mean', 'p_median', 'range', 'std'], fill_color='paleturquoise', align='left'),
        cells=dict(values=[
            df_filtered['p_mean'], 
            df_filtered['p_median'], 
            df_filtered['range'], 
            df_filtered['std']
        ])
    )]
    return go.Figure(data=table_data)

3. 关键修改说明

  • 修正Output属性:把'graph'改成'figure',这是Graph组件用来接收可视化数据的正确属性。
  • 添加State参数:通过State('plot', 'figure')获取当前图表的实时figure数据,这样就能拿到每个trace的name。
  • 处理trace name的提取:你的trace name格式是"{test}, #rounds: {n_rounds}",所以需要用split(',')[0].strip()提取出纯test名称,才能匹配df_lists的key。
  • 边界情况处理:
    • 页面刚加载时hoverData为空,返回一个空表格避免报错。
    • 如果找不到对应test的df,返回提示表格提升用户体验。

4. 额外注意事项

确保df_lists的key和你提取的trace name完全一致(比如大小写、空格都要匹配),否则会出现找不到数据的情况。如果你的trace name格式有变化,要同步调整提取逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 17:15:48