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

Plotly散点图悬停文本如何正确显示非数值变量Device与variable

解决Plotly散点图悬停文本中Device和variable字段不显示的问题
  • 问题原因:Plotly的hovertemplate无法直接引用DataFrame的原始列名,仅能识别trace内置属性(如%{x}、%{y})或custom_data传入的自定义数据。你当前代码里直接用%{Device}和{symbol}不符合模板规则,导致无法正确解析。
  • 解决步骤:
    1. 在px.scatter的custom_data参数中加入Device和variable,将需要显示的非数值变量传入trace的自定义数据池
    2. 修改hovertemplate,用%{custom_data[index]}格式调用对应位置的自定义数据
    3. 修正模板里的语法错误(比如引号不匹配问题)

修改后的完整代码:

df3 = df2.query('variable==@signals').groupby('path').first() 

fig_general = px.scatter(df3
                          , x = "time"
                          , y = 'value'
                          , custom_data = ['Path', 'Device', 'variable']  # 新增Device和variable到自定义数据
                          , color = 'Device'
                          , symbol = 'variable'
                          , hover_name = "Path"
                          , opacity = 0.6
                          , template = 'plotly_dark'
                          , marginal_y = "rug"
                          )
fig_general.update_layout(
                           transition_duration = 500
                          , autosize = True
                          , height = 700
                          , hovermode = 'closest'
                          )
fig_general.update_traces(marker = dict(
                                        size = 14
                                        )
                            , hovertemplate="<br>".join([
                                                        "Device: %{custom_data[1]}"  # 对应custom_data中的Device
                                                        , "variable: %{custom_data[2]}"  # 对应custom_data中的variable
                                                        , "time: %{x}"
                                                        , "value: %{y}"
                                                    ]) + "<extra></extra>"  # 隐藏默认trace名称,优化悬停文本展示
                          )

关键说明:

  • custom_data的顺序需与hovertemplate里的索引一一对应,比如示例中custom_data[1]对应Device,custom_data[2]对应variable
  • <extra></extra>用于移除Plotly默认显示的trace标识(如"trace 0"),让悬停文本更简洁

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:05:28