Search code examples
vega-lite

Brush zooming in X and Y in Vega-lite


In Vega-lite, is it possible to zoom in to a plot with a brush in the X and Y direction at the same time? Using this example as a base: https://vega.github.io/vega-lite/examples/interactive_overview_detail.html

I tried encoding the Y, but I'm not sure how to point "scale": {"domain": {"selection": "brush"}} in the Y axis direction.

unexpected result

If not, is it possible to achieve similar results with the "bind": "scales"? The goal is to have a "key-map" of the chart with a zoom-in, and a small box showing where the zoom is on the broader time-series.

Code I've been trying with that example:

{
  "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
  "data": {"url": "data/sp500.csv"},
  "vconcat": [{
    "width": 480,
    "mark": "area",
    "encoding": {
      "x": {
        "field": "date",
        "type": "temporal",
        "scale": {"domain": {"selection": "brush"}},
        "axis": {"title": ""}
      },
      "y": {"field": "price", 
      "type": "quantitative",
      "scale": {"domain": {"selection": "brush"}}
}
    }
  }, {
    "width": 480,
    "height": 60,
    "mark": "area",
    "selection": {
      "brush": {"type": "interval", "encodings": ["x","y"]}
    },
    "encoding": {
      "x": {
        "field": "date",
        "type": "temporal"
      },
      "y": {
        "field": "price",
        "type": "quantitative",
        "axis": {"tickCount": 3, "grid": false}
      }
    }
  }]
}`

Solution

  • You can do this by specifying the field or the encoding within the domain; for example:

    "domain": {"selection": "brush", "encoding": "y"}
    

    Putting this into your example looks like this (view live):

    {
      "$schema": "https://vega.github.io/schema/vega-lite/v4.json",
      "data": {"url": "data/sp500.csv"},
      "vconcat": [
        {
          "width": 480,
          "mark": "area",
          "encoding": {
            "x": {
              "field": "date",
              "type": "temporal",
              "scale": {"domain": {"selection": "brush", "encoding": "x"}},
              "axis": {"title": ""}
            },
            "y": {
              "field": "price",
              "type": "quantitative",
              "scale": {"domain": {"selection": "brush", "encoding": "y"}}
            }
          }
        },
        {
          "width": 480,
          "height": 60,
          "mark": "area",
          "selection": {"brush": {"type": "interval", "encodings": ["x", "y"]}},
          "encoding": {
            "x": {"field": "date", "type": "temporal"},
            "y": {
              "field": "price",
              "type": "quantitative",
              "axis": {"tickCount": 3, "grid": false}
            }
          }
        }
      ]
    }
    

    enter image description here