the21st
the21st

Reputation: 1096

Vega-lite line mark with aggregation – show tooltip at a distance

This is a follow-up to this question, with aggregation added to the spec.

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", "timeUnit": "year"},
    "y": {"field": "price", "type": "quantitative", "aggregate": "average"},
    "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.

Upvotes: 1

Views: 400

Answers (1)

davidebacci
davidebacci

Reputation: 30219

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"},
  "transform": [
    {"timeUnit": "year", "field": "date", "as": "year"},
    {
      "aggregate": [{"op": "average", "field": "price", "as": "price"}],
      "groupby": ["symbol", "year"]
    }
  ],
  "encoding": {
    "x": {"field": "year", "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}
      }
    }
  ]
}

Upvotes: 1

Related Questions