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

Deneb中如何实现无需硬编码的动态Tooltip?

解决方案

要实现Tooltip自动展示所有选中Ticker的对应日期数值,无需硬编码,你可以通过Vega-Lite的表达式筛选和动态生成tooltip内容来实现。以下是修改后的完整代码:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "params": [
    {
      "name": "hover",
      "select": {
        "type": "point",
        "fields": ["Date"],
        "nearest": true,
        "on": "mouseover",
        "clear": "mouseout"
      }
    }
  ],
  "data": {"name": "dataset"},
  "title": {
    "text": {"expr": "data('dataset')[0]['title']"},
    "anchor": "start",
    "subtitle": {"expr": "data('dataset')[0]['title']"}
  },
  "encoding": {"x": {"field": "Date", "type": "temporal"}},
  "layer": [
    {
      "mark": "line",
      "encoding": {
        "y": {"field": "Sum of Price", "type": "quantitative", "title": "Price"},
        "color": {"field": "Ticker", "type": "nominal", "scale": {"range": {"field": "Colour"}}}
      }
    },
    {
      "mark": {"type": "rule", "color": "gray", "y": 0, "y2": {"expr": "height"}},
      "encoding": {
        "opacity": {
          "condition": {"param": "hover", "empty": false, "value": 0.5},
          "value": 0
        },
        "tooltip": [
          {"field": "Date", "type": "temporal", "title": "日期"},
          {
            "expr": "data('dataset').filter(d => d.Date === hover['Date']).map(d => ({name: d.Ticker, value: format(d['Sum of Price'], '.2f')}))",
            "type": "nominal"
          }
        ]
      },
      "transform": [{"filter": {"param": "hover"}}]
    }
  ],
  "config": {
    "view": {"stroke": "transparent"},
    "axis": {"domain": false, "tickColor": "lightGray"},
    "style": {"cell": {"stroke": "transparent"}}
  }
}

关键修改说明

  • 顶层Hover参数:将hover参数移至图表顶层,确保全上下文可访问,避免层级隔离导致的日期匹配失败。
  • 动态Tooltip生成:通过表达式data('dataset').filter(...)筛选出当前hover日期对应的所有数据点,再用map将每个Ticker和价格格式化为键值对数组。Vega会自动将数组渲染为多行Tooltip,每条对应一个Ticker的数值。
  • 简化层级结构:移除了原代码中冗余的内层Layer,让图表逻辑更清晰,同时保证Rule仅在hover触发时显示。
  • 数值格式化:使用format()函数对价格保留两位小数,提升Tooltip可读性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 13:30:04