Vega-Lite: Multi-layer graphics

Data 304

Stack ’em up

To define a layered chart, put multiple specifications into an array under the layer property.

{  ...,
  "data": ...   // shared data (if any)
  ...,          // other shared properties
  "layer": [    // array of layer specs
    { ... },    // first layer spec
    { ... },    // second layer spec
    ...         // etc
  ]
}
  • Vega-Lite will (by default) expand the domains of the scales to include the data from all the layers.

  • Each subsequent layer sits “on top of” the previous layers

Uses for layers

  • Different marks in different layers (e.g., point and lines)
  • Different data in different layers
  • Data layer and model layer (e.g., scatterplot & regression line)
  • Data layer and annotation layer (e.g., alternative guides)
  • etc.

Example: Same data, two marks

  "data": {"url": "data/cars.json"},
  "layer": [
    {"mark": {"type": "line", "opacity": 0.8},
     "encoding": {
       "y": {"field": "Miles_per_Gallon", "type": "quantitative", "aggregate": "mean"},
       "color": {"field": "Origin"},
       "detail": {"field": "Cylinders"}, 
       "x": {"field": "Year", "type": "temporal"}
      }
    },

    {"mark": "point",
    "encoding": {
       "y": {"field": "Miles_per_Gallon", "type": "quantitative", "aggregate": "mean"},
       "color": {"field": "Origin"},
       "detail": {"field": "Cylinders"}, 
       "x": {"field": "Year", "type": "temporal"}
      }
  }]

Don’t repeat yourself

Elements of the specification that are shared across all layers can be placed outside the layers property.

Here we can reduce the layer part to just specifying the mark.

  "encoding": {
       "y": {"field": "Miles_per_Gallon", "type": "quantitative", "aggregate": "mean"},
       "color": {"field": "Origin"},
       "detail": {"field": "Cylinders"}, 
       "x": {"field": "Year", "type": "temporal"}
  },
  "layer": [
    {"mark": {"type": "line", "opacity": 0.7}},
    {"mark": "point"}
  ]

Layers and facets

To combine layers and facets, we must use the facet operator.

{ ...,
  "facet": {"column": {"field": "Origin"}},
  "spec": {
    "encoding": {"color": {"field": "Origin"}},
    "layer": [
      {...},          // layer for points
      {...},          // layer for rule 
      {...}           // layer for text
    ]
  }
}

Text can add info, replace guides