This document is adapted from the Interactive Charts section of the Altair Example Gallery.

Our first step is to set up our environment:

library("altair")
library("tibble")
library("dplyr")
library("tidyr")
library("jsonlite")

vega_data <- import_vega_data()

Interactive Average

Altair example

The plot below uses an interval selection, which causes the chart to include an interactive brush (shown in grey). The brush selection parameterizes the red guideline, which visualizes the average value within the selected interval.

Data

## Observations: 1,461
## Variables: 6
## $ date          <dttm> 2012-01-01, 2012-01-02, 2012-01-03, 2012-01-04, 2…
## $ precipitation <dbl> 0.0, 10.9, 0.8, 20.3, 1.3, 2.5, 0.0, 0.0, 4.3, 1.0…
## $ temp_max      <dbl> 12.8, 10.6, 11.7, 12.2, 8.9, 4.4, 7.2, 10.0, 9.4, …
## $ temp_min      <dbl> 5.0, 2.8, 7.2, 5.6, 2.8, 2.2, 2.8, 2.8, 5.0, 0.6, …
## $ wind          <dbl> 4.7, 4.5, 2.3, 4.7, 6.1, 2.2, 2.3, 2.0, 3.4, 3.4, …
## $ weather       <chr> "drizzle", "rain", "rain", "rain", "rain", "rain",…

Chart

Interactive Chart with Cross-Highlight

Altair example

This example shows an interactive chart where selections in one portion of the chart affect what is shown in other panels. Click on the bar chart to see a detail of the distribution in the upper panel.

Data

glimpse(fromJSON(vega_data$movies$url))
## Observations: 3,201
## Variables: 16
## $ Title                  <chr> "The Land Girls", "First Love, Last Rites…
## $ US_Gross               <int> 146083, 10876, 203134, 373615, 1009819, 2…
## $ Worldwide_Gross        <dbl> 146083, 10876, 203134, 373615, 1087521, 2…
## $ US_DVD_Sales           <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N…
## $ Production_Budget      <int> 8000000, 300000, 250000, 300000, 1000000,…
## $ Release_Date           <chr> "Jun 12 1998", "Aug 07 1998", "Aug 28 199…
## $ MPAA_Rating            <chr> "R", "R", NA, NA, "R", NA, "R", "R", "R",…
## $ Running_Time_min       <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, N…
## $ Distributor            <chr> "Gramercy", "Strand", "Lionsgate", "Fine …
## $ Source                 <chr> NA, NA, NA, NA, "Original Screenplay", NA…
## $ Major_Genre            <chr> NA, "Drama", "Comedy", "Comedy", "Drama",…
## $ Creative_Type          <chr> NA, NA, NA, NA, "Contemporary Fiction", N…
## $ Director               <chr> NA, NA, NA, NA, NA, NA, "Christopher Nola…
## $ Rotten_Tomatoes_Rating <int> NA, NA, NA, 13, 62, NA, NA, NA, 25, 86, 8…
## $ IMDB_Rating            <dbl> 6.1, 6.9, 6.8, NA, 3.4, NA, 7.7, 3.8, 5.8…
## $ IMDB_Votes             <int> 1071, 207, 865, NA, 165, NA, 15133, 353, …

Chart

Interactive Crossfilter

Altair example

This example shows a multi-panel view of the same data, where you can interactively select a portion of the data in any of the panels to highlight that portion in any of the other panels.

Note: alt$repeat() must be translated to alt$\x60repeat\x60().

Data

glimpse(fromJSON(vega_data$flights_2k$url))
## Observations: 2,000
## Variables: 5
## $ date        <chr> "2001/01/14 21:55", "2001/03/26 20:15", "2001/03/05 …
## $ delay       <int> 0, -11, -3, 12, 2, 47, 3, -4, 4, 0, 18, -7, -10, 23,…
## $ distance    <int> 480, 507, 714, 342, 373, 189, 872, 723, 318, 487, 23…
## $ origin      <chr> "SAN", "PHX", "ELP", "SJC", "SMF", "DAL", "AUS", "GE…
## $ destination <chr> "SMF", "SLC", "LAX", "SNA", "LAX", "AUS", "PHX", "OA…

Chart

Interactive Rectangular Brush

Altair example

This example shows how to add a simple rectangular brush to a scatter plot. By clicking and dragging on the plot, you can highlight points within the range.

Data

glimpse(vega_data$cars())
## Observations: 406
## Variables: 9
## $ Acceleration     <dbl> 12.0, 11.5, 11.0, 12.0, 10.5, 10.0, 9.0, 8.5, 1…
## $ Cylinders        <dbl> 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 8, 8, 8,…
## $ Displacement     <dbl> 307, 350, 318, 304, 302, 429, 454, 440, 455, 39…
## $ Horsepower       <dbl> 130, 165, 150, 150, 140, 198, 220, 215, 225, 19…
## $ Miles_per_Gallon <dbl> 18, 15, 18, 16, 17, 15, 14, 14, 14, 15, NaN, Na…
## $ Name             <chr> "chevrolet chevelle malibu", "buick skylark 320…
## $ Origin           <chr> "USA", "USA", "USA", "USA", "USA", "USA", "USA"…
## $ Weight_in_lbs    <dbl> 3504, 3693, 3436, 3433, 3449, 4341, 4354, 4312,…
## $ Year             <dttm> 1970-01-01, 1970-01-01, 1970-01-01, 1970-01-01…

Chart

Interactive Scatter Plot and Linked Layered Histogram

Altair example

This example shows how to link a scatter plot and a histogram together such that clicking on a point in the scatter plot will isolate the distribution corresponding to that point, and vice versa.

Data

Definition

source <- tibble(
  gender = c(rep("M", 1000), rep("F", 1000)),
  height = c(rnorm(1000, 69, 7), rnorm(1000, 64, 6)),
  weight = c(rnorm(1000, 195.8, 144), rnorm(1000, 167, 100)),
  age = c(rnorm(1000, 45, 8), rnorm(1000, 51, 6))
)
glimpse(source)
## Observations: 2,000
## Variables: 4
## $ gender <chr> "M", "M", "M", "M", "M", "M", "M", "M", "M", "M", "M", "M…
## $ height <dbl> 71.36949, 55.99202, 77.97588, 70.46886, 76.06890, 61.5016…
## $ weight <dbl> -55.99695, -162.81368, 192.32604, 289.99114, 235.61485, 2…
## $ age    <dbl> 40.37951, 50.98795, 43.18294, 30.23115, 40.06121, 42.5840…

Chart

Multi-Line Highlight

Altair example

This multi-line chart uses an invisible Voronoi tessellation to handle mouseover to identify the nearest point and then highlight the line on which the point falls. It is adapted from the Vega-Lite example.

Data

glimpse(vega_data$stocks())
## Observations: 560
## Variables: 3
## $ symbol <chr> "MSFT", "MSFT", "MSFT", "MSFT", "MSFT", "MSFT", "MSFT", "…
## $ date   <dttm> 2000-01-01, 2000-02-01, 2000-03-01, 2000-04-01, 2000-05-…
## $ price  <dbl> 39.81, 36.35, 43.22, 28.37, 25.45, 32.54, 28.40, 28.40, 2…

Chart

Multi-Line Tooltip

Altair Example

This example shows how you can use selections and layers to create a multi-line tooltip that tracks the x position of the cursor.

To find the x-position of the cursor, we employ a little trick: we add some transparent points with only an x encoding (no y encoding) and tie a nearest selection to these, tied to the x field.

Data

Definition

set.seed(42)

category <- c("A", "B", "C")
x <- seq(1, 100)

data <-
  crossing(
    category = c("A", "B", "C"),
    x = seq(1, 100)
  ) %>%
  mutate(y = rnorm(n()) %>% round(2)) %>%
  group_by(category) %>%
  mutate(y = cumsum(y)) %>%
  ungroup()
glimpse(data)
## Observations: 300
## Variables: 3
## $ category <chr> "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", "A", …
## $ x        <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, …
## $ y        <dbl> 1.37, 0.81, 1.17, 1.80, 2.20, 2.09, 3.60, 3.51, 5.53, 5…

Chart

Multi-panel Scatter Plot with Linked Brushing

Altair example

Data

glimpse(vega_data$cars())
## Observations: 406
## Variables: 9
## $ Acceleration     <dbl> 12.0, 11.5, 11.0, 12.0, 10.5, 10.0, 9.0, 8.5, 1…
## $ Cylinders        <dbl> 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 8, 8, 8,…
## $ Displacement     <dbl> 307, 350, 318, 304, 302, 429, 454, 440, 455, 39…
## $ Horsepower       <dbl> 130, 165, 150, 150, 140, 198, 220, 215, 225, 19…
## $ Miles_per_Gallon <dbl> 18, 15, 18, 16, 17, 15, 14, 14, 14, 15, NaN, Na…
## $ Name             <chr> "chevrolet chevelle malibu", "buick skylark 320…
## $ Origin           <chr> "USA", "USA", "USA", "USA", "USA", "USA", "USA"…
## $ Weight_in_lbs    <dbl> 3504, 3693, 3436, 3433, 3449, 4341, 4354, 4312,…
## $ Year             <dttm> 1970-01-01, 1970-01-01, 1970-01-01, 1970-01-01…

Chart

Multiple Interactions

Altair example

This example shows how multiple user inputs can be layered onto a chart. The four inputs have functionality as follows:

  • Dropdown: Filters the movies by genre
  • Radio Buttons: Highlights certain films by Worldwide Gross
  • Mouse Drag and Scroll: Zooms the x and y scales to allow for panning.

Chart

ratings <- list("G", "NC-17", "PG", "PG-13", "R")
genres <- 
  list("Action", "Adventure", "Black Comedy", "Comedy", "Concert/Performance",
       "Documentary", "Drama", "Horror", "Musical", "Romantic Comedy", 
       "Thriller/Suspense", "Western")

base <-
  alt$Chart(vega_data$movies$url, width = 200, height = 200)$
  mark_point(filled = TRUE)$
  transform_calculate(
    Rounded_IMDB_Rating = "floor(datum.IMDB_Rating)",
    Hundred_Million_Production = "datum.Production_Budget > 100000000.0 ? 100 : 10",
    Release_Year = "year(datum.Release_Date)"
  )$transform_filter(
    "datum.IMDB_Rating > 0"
  )$transform_filter(
    alt$FieldOneOfPredicate(field="MPAA_Rating", oneOf=ratings)
  )$encode(
    x = alt$X(
      "Worldwide_Gross:Q", 
      scale = alt$Scale(domain=c(100000,10**9), clamp = TRUE)
    ),
    y = "IMDB_Rating:Q",
    tooltip = "Title:N"
  )

# A slider filter
year_slider <- alt$binding_range(min = 1969, max = 2018, step = 1)
slider_selection <- 
  alt$selection_single(
    bind = year_slider, 
    fields = list("Release_Year"),
    name = "Release Year_"
  )

filter_year <- base$
  add_selection(slider_selection)$
  transform_filter(slider_selection)$
  properties(title = "Slider Filtering")

# A dropdown filter
genre_dropdown <- alt$binding_select(options = genres)
genre_select <- 
  alt$selection_single(
    fields = list("Major_Genre"), 
    bind = genre_dropdown,
    name = "Genre"
  )

filter_genres <- 
  base$
  add_selection(genre_select)$
  transform_filter(genre_select)$
  properties(title="Dropdown Filtering")

#color changing marks
rating_radio <- alt$binding_radio(options=ratings)

rating_select <- 
  alt$selection_single(
    fields = list("MPAA_Rating"), 
    bind = rating_radio, 
    name = "Rating"
  )

rating_color_condition <- 
  alt$condition(
    rating_select,
    alt$Color("MPAA_Rating:N", legend = NULL),
    alt$value("lightgray")
  )

highlight_ratings <-
  base$
  add_selection(rating_select)$
  encode(
    color = rating_color_condition
  )$
  properties(title = "Radio Button Highlighting")

# Boolean selection for format changes
input_checkbox <- alt$binding_checkbox()
checkbox_selection <-
  alt$selection_single(bind = input_checkbox, name = "Big Budget Films")

size_checkbox_condition <-
  alt$condition(
    checkbox_selection,
    alt$SizeValue(25),
    alt$Size("Hundred_Million_Production:Q")
  )

budget_sizing <-
  base$
  add_selection(checkbox_selection)$
  encode(
    size = size_checkbox_condition)$
  properties(title = "Checkbox Formatting")

(filter_year | filter_genres) & (highlight_ratings | budget_sizing)

Scatter Plot and Histogram with Interval Selection

Altair example

This example shows how to link a scatter plot and a histogram together such that an interval selection in the histogram will plot the selected values in the scatter plot.

Note that both subplots need to know about the mbin field created by the transform_bin method. In order to achieve this, the data is not passed to the Chart() instances creating the subplots, but directly in the hconcat() function, which joins the two plots together.

Data

Definition

glimpse(source)
## Observations: 100
## Variables: 3
## $ x <dbl> -0.0046207678, 0.7602421677, 0.0389909129, 0.7350721416, -0.14…
## $ y <dbl> 1.33491259, -0.86927176, 0.05548695, 0.04906691, -0.57835573, …
## $ m <dbl> 16.02914, 15.91477, 14.99754, 15.13601, 14.27985, 14.80188, 13…

Chart

Selection Detail Example

Altair example

This example shows a selection that links two views of data: the left panel contains one point per object, and the right panel contains one line per object. Clicking on either the points or lines will select the corresponding objects in both views of the data.

The challenge lies in expressing such hierarchical data in a way that Altair can handle. We do this by merging the data into a “long form” dataframe, and aggregating identical metadata for the final plot.

Data

Definition

glimpse(data)
## Observations: 1,000
## Variables: 5
## $ id    <int> 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1…
## $ time  <int> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17,…
## $ value <dbl> 0.8029327, 0.2294558, -1.6986693, -1.0342785, -2.6368187, …
## $ x     <dbl> -0.2484829, -0.2484829, -0.2484829, -0.2484829, -0.2484829…
## $ y     <dbl> 1.001113, 1.001113, 1.001113, 1.001113, 1.001113, 1.001113…

Chart