This document is adapted from the linked-brush scatter-plot example found in the Altair documentation.

A goal of Vega-Lite is to implement a declarative grammar not only of visualization, but also of interaction. The core concept of this interactive grammar is the selection object. Selection mechanisms are implemented in Vega-Lite and are provided by Altair.

Let’s start again with our basic plot from the Getting Started article:

library("altair")

vega_data <- import_vega_data()

chart_static <- 
  alt$Chart(vega_data$cars())$
  mark_point()$
  encode(
    x = "Horsepower:Q",
    y = "Miles_per_Gallon:Q",
    color = "Origin:N"
  )

chart_static

Nothing new, so far. Our first step towards interactivity is to create a selection mechanism. This is an interval selection, other types of selections are detailed in the API reference.

brush <- alt$selection_interval()

We can create a new chart where the brush is bound using the selection property:

chart_brush <- chart_static$add_selection(brush) 

chart_brush

You can click-and-drag to draw a selection-box, then move it around. So far, so good, but it does not really do much. Let’s change that.

We need to “tell” the encoding to pay attention to the selection. We could do that by respecifying the entire chart. We introduce the condition() method to specify a light-gray color for observations that are not selected.

chart_selection <-
  alt$Chart(vega_data$cars())$
  mark_point()$
  encode(
    x = "Horsepower:Q",
    y = "Miles_per_Gallon:Q",
    color = alt$condition(brush, "Origin:N", alt$value("lightgray"))
  )$
  mark_point()$
  add_selection(brush) 

# chart_selection

This works, but it appears there is an easier way. It appears that you can call the encode() method to overwrite specific encodings for an existing chart. Thus, we have a chart where you can “see” the effect of your selection.

chart_selection <- 
  chart_brush$encode(
    color = alt$condition(brush, "Origin:N", alt$value("lightgray"))
  )

chart_selection

Not too shabby, eh!

The capabilities become more-apparent when we combine charts. Let’s create charts that look at different aspects of the data. We will use chart_selection as our base-chart, then modify as needed.

chart_mpg <- chart_selection$properties(width = 250, height = 250)

chart_disp <- 
  chart_mpg$encode(
    x = "Displacement:Q"
  )

In essence, chart_mpg is a smaller version of chart_selection; chart_disp is derived from chart_mpg, showing displacement on its x-axis, rather than mpg. It remains to compose these into a compound chart and display:

chart_compound <- (chart_mpg | chart_disp)

chart_compound

You can select observations from either side. This is just a taste of what we can do using Vega-Lite, using the Altair API.