Search code examples
jsonchartsvisualizationvega-litevega

Vega-lite line mark show tooltip at a distance


I have the following chart in VegaLite:

(open in vega editor)

{
  "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
  "description": "Stock prices of 5 Tech Companies over Time.",
  "data": {"url": "data/stocks.csv"},
  "mark": {"type": "line", "tooltip": true},
  "encoding": {
    "x": {"field": "date", "type": "temporal"},
    "y": {"field": "price", "type": "quantitative"},
    "color": {"field": "symbol", "type": "nominal"}
  }
}

Notice the "tooltip": true - I want to be able to show the values on mouse hover. However, for the tooltip to show up, I have to hover my cursor exactly at the single pixel of the lines' data points.

I would like to show the tooltip already at some distance, let's say 20 pixels. Or even just anywhere, using the nearest data point. Is that possible without a lot of extra code in the spec? I especially want to avoid listing all the values from the legend, like here.

I'd also like for the tooltip approach to work with multiple layers, e.g. in a combined line+bar chart.


Solution

  • You need to add the "nearest" attribute to a selection parameter. There are some limitations and workarounds documented here for your use case.

    https://vega.github.io/vega-lite/docs/selection.html#nearest

    Edit:

    enter image description here

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v5.json",
      "description": "Stock prices of 5 Tech Companies over Time.",
      "data": {"url": "data/stocks.csv"},
      "encoding": {
        "x": {"field": "date", "type": "temporal"},
        "y": {"field": "price", "type": "quantitative"},
        "color": {"field": "symbol", "type": "nominal"}
      },
      "layer": [
        {"mark": {"type": "line"}},
        {
          "params": [
            {
              "name": "paintbrush",
              "select": {"type": "point", "on": "mouseover", "nearest": true}
            }
          ],
          "mark": {"type": "circle", "tooltip": true},
          "encoding": {
            "color": {
              "condition": {
                "param": "paintbrush",
                "field": "symbol",
                "type": "ordinal"
              },
              "value": "transparent"
            },
            "size": {"value": 75}
          }
        }
      ]
    }