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

如何在Vega-Lite图表中获取两个独立图层的tooltip信息

解决Vega-Lite双图层Tooltip同时展示数据的方案
  • 方法1:顶层统一配置Tooltip
    在图表顶层添加tooltip: {"content": "data"},同时在两个图层的encoding中显式声明需要展示的Tooltip字段(即使字段未用于视觉编码)。Vega-Lite会自动合并所有图层的Tooltip字段,悬停时展示完整信息。示例结构:

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "layer": [
        {
          "mark": "line",
          "encoding": {
            "x": {"field": "date", "type": "temporal"},
            "y": {"field": "value1", "type": "quantitative"},
            "tooltip": [{"field": "date"}, {"field": "value1", "title": "数值1"}]
          }
        },
        {
          "mark": "bar",
          "encoding": {
            "x": {"field": "date", "type": "temporal"},
            "y": {"field": "value2", "type": "quantitative"},
            "tooltip": [{"field": "value2", "title": "数值2"}]
          }
        }
      ],
      "tooltip": {"content": "data"}
    }
    
  • 方法2:合并数据集+透明Tooltip图层
    若两个图层用不同数据集,先通过transform.lookup合并数据,再添加一个透明点图层承载完整Tooltip,确保悬停时关联所有数据。示例:

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "data": {"name": "data1"},
      "transform": [
        {
          "lookup": "date",
          "from": {"data": {"name": "data2"}, "key": "date", "fields": ["value2"]}
        }
      ],
      "layer": [
        {
          "mark": "line",
          "encoding": {
            "x": {"field": "date", "type": "temporal"},
            "y": {"field": "value1", "type": "quantitative"}
          }
        },
        {
          "mark": "bar",
          "encoding": {
            "x": {"field": "date", "type": "temporal"},
            "y": {"field": "value2", "type": "quantitative"}
          }
        },
        {
          "mark": "point",
          "encoding": {
            "x": {"field": "date", "type": "temporal"},
            "opacity": {"value": 0},
            "tooltip": [
              {"field": "date"},
              {"field": "value1", "title": "数值1"},
              {"field": "value2", "title": "数值2"}
            ]
          }
        }
      ]
    }
    
  • 关键注意事项

    • 确保两个图层的对齐字段(如x轴字段)完全匹配,否则Tooltip无法正确关联数据。
    • 不要在单个图层中设置tooltip: null,这会阻止该图层数据被合并到全局Tooltip。
    • 多数据集场景必须先通过lookup或预合并对齐关联字段,才能实现Tooltip的联合展示。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 17:42:00