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

Vega-Lite折线图:仅在hover时标记线条终点

解决Vega-Lite折线图终点标注的两个问题

针对你遇到的两个问题,这里给出具体的修改方案:

问题1:仅标记end_period最大值对应的终点

通过**窗口计算(window transform)**筛选出每个Geography分组下end_period最大的数据点,只对这些点添加文本标注。

问题2:仅在hover时显示文本标注

通过选择器(selection)配合条件判断(condition),控制文本标记仅在hover线条或终点时显示,默认状态隐藏。

修改后的完整配置

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "data": {"url": "你的数据源地址"}, // 替换为实际数据源路径
  "encoding": {
    "x": {"field": "end_period", "type": "temporal"},
    "y": {"field": "value", "type": "quantitative"},
    "color": {"field": "Geography", "type": "nominal"}
  },
  "layer": [
    // 基础折线图层
    {
      "mark": "line"
    },
    // 透明终点触发点(提升hover交互灵敏度)
    {
      "transform": [
        {
          "window": [{"field": "end_period", "op": "max", "as": "max_period"}],
          "groupby": ["Geography"]
        },
        {"filter": "datum.end_period === datum.max_period"}
      ],
      "mark": {"type": "point", "opacity": 0},
      "selection": {
        "hoverLine": {
          "type": "single",
          "on": "mouseover",
          "nearest": true,
          "fields": ["Geography"],
          "empty": "none"
        }
      }
    },
    // 仅hover时显示的终点文本标注
    {
      "transform": [
        {
          "window": [{"field": "end_period", "op": "max", "as": "max_period"}],
          "groupby": ["Geography"]
        },
        {"filter": "datum.end_period === datum.max_period"}
      ],
      "mark": {"type": "text", "align": "left", "dx": 5},
      "encoding": {
        "text": {"field": "Geography", "type": "nominal"},
        "opacity": {
          "condition": {"selection": "hoverLine", "value": 1},
          "value": 0
        }
      }
    }
  ]
}

关键修改说明

  • 筛选终点:用window变换为每个Geography分组计算最大end_period,再通过filter仅保留对应终点数据,避免所有点被标注。
  • hover显示控制:创建hoverLine选择器,通过nearest: true精准捕捉hover目标;文本标记的opacity通过条件绑定选择器,未hover时完全透明,hover时显示。
  • 透明触发点:如果直接hover折线交互不灵敏,透明的终点点可以提升触发准确性,不影响视觉效果。

内容的提问来源于stack exchange,提问作者mpmm-vis

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 12:04:57