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

Our first step is to set up our environment:

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

weather <- vega_data$seattle_weather()

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

Chart

brush <- alt$selection(type = "interval", encodings = list("x"))

bars <- 
  alt$Chart()$
  mark_bar()$
  encode(
    x = alt$X("date:O", timeUnit="month"),
    y = "mean(precipitation):Q",
    opacity = alt$condition(
      brush, 
      alt$OpacityValue(1), 
      alt$OpacityValue(0.7)
    )
  )$
  properties(selection = brush)

line <- 
  alt$Chart()$
  mark_rule(color = "firebrick")$
  encode(
    y = "mean(precipitation):Q",
    size = alt$SizeValue(3)
  )$
  transform_filter(brush$ref())

chart <- alt$layer(bars, line, data = weather)

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))
## Rows: 3,201
## Columns: 16
## $ Title                  <chr> "The Land Girls", "First Love, Last Rites", "I…
## $ US_Gross               <int> 146083, 10876, 203134, 373615, 1009819, 24551,…
## $ Worldwide_Gross        <dbl> 146083, 10876, 203134, 373615, 1087521, 262455…
## $ US_DVD_Sales           <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA…
## $ Production_Budget      <int> 8000000, 300000, 250000, 300000, 1000000, 1600…
## $ Release_Date           <chr> "Jun 12 1998", "Aug 07 1998", "Aug 28 1998", "…
## $ MPAA_Rating            <chr> "R", "R", NA, NA, "R", NA, "R", "R", "R", NA, …
## $ Running_Time_min       <int> NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA…
## $ Distributor            <chr> "Gramercy", "Strand", "Lionsgate", "Fine Line"…
## $ Source                 <chr> NA, NA, NA, NA, "Original Screenplay", NA, NA,…
## $ Major_Genre            <chr> NA, "Drama", "Comedy", "Comedy", "Drama", NA, …
## $ Creative_Type          <chr> NA, NA, NA, NA, "Contemporary Fiction", NA, NA…
## $ Director               <chr> NA, NA, NA, NA, NA, NA, "Christopher Nolan", N…
## $ Rotten_Tomatoes_Rating <int> NA, NA, NA, 13, 62, NA, NA, NA, 25, 86, 81, 84…
## $ IMDB_Rating            <dbl> 6.1, 6.9, 6.8, NA, 3.4, NA, 7.7, 3.8, 5.8, 7.0…
## $ IMDB_Votes             <int> 1071, 207, 865, NA, 165, NA, 15133, 353, 3275,…

Chart

pts <- alt$selection(type = "single", encodings = list("x"))

rect <- 
  alt$Chart(vega_data$movies$url)$
  mark_rect()$
  encode(
    x = alt$X("IMDB_Rating:Q", bin = TRUE),
    y = alt$Y("Rotten_Tomatoes_Rating:Q", bin=TRUE),
    color = alt$Color(
      "count()",
      scale = alt$Scale(scheme = "greenblue"),
      legend = alt$Legend(title = "Total Records")
    )
  )

circ <- 
  rect$
  mark_point()$
  encode(
    color = alt$ColorValue("grey"),
    size = alt$Size(
      "count()",
      legend = alt$Legend(title = "Records in Selection")
    )
  )$
  transform_filter(pts$ref())

bar <- 
  alt$Chart(vega_data$movies$url)$
  mark_bar()$
  encode(
    x = "Major_Genre:N",
    y = "count()",
    color = alt$condition(
      pts, 
      alt$ColorValue("steelblue"), 
      alt$ColorValue("grey"))
  )$
  properties(
    selection = pts,
    width = 550, 
    height = 200
  )

chart <- 
  ((rect + circ) & bar)$ 
  resolve_legend(color = "independent", size = "independent")

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))
## Rows: 2,000
## Columns: 5
## $ date        <chr> "2001/01/14 21:55", "2001/03/26 20:15", "2001/03/05 14:55…
## $ delay       <int> 0, -11, -3, 12, 2, 47, 3, -4, 4, 0, 18, -7, -10, 23, 7, -…
## $ distance    <int> 480, 507, 714, 342, 373, 189, 872, 723, 318, 487, 239, 45…
## $ origin      <chr> "SAN", "PHX", "ELP", "SJC", "SMF", "DAL", "AUS", "GEG", "…
## $ destination <chr> "SMF", "SLC", "LAX", "SNA", "LAX", "AUS", "PHX", "OAK", "…

Chart

brush <- alt$selection_interval(encodings = list("x"))

# Define the base chart, with the common parts of the
# background and highlights
base <- 
  alt$Chart(vega_data$flights_2k$url)$
  mark_bar()$
  encode(
    x = alt$X(
      alt$`repeat`("column"), 
      type = "quantitative", 
      bin = alt$Bin(maxbins=20)
    ),
    y = "count()"
  )$
  properties(width = 160, height = 130)

# blue background with selection
background <- base$properties(selection = brush)

# yellow highlights on the transformed data
highlight <- 
  base$
  encode(
    color = alt$value("goldenrod")
  )$
  transform_filter(brush$ref())

# layer the two charts & repeat
chart <- 
  (background + highlight)$ 
  transform_calculate("time", "hours(datum.date)")$
  `repeat`(column = list("distance", "delay", "time"))

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())
## Rows: 406
## Columns: 9
## $ Name             <chr> "chevrolet chevelle malibu", "buick skylark 320", "p…
## $ Miles_per_Gallon <dbl> 18, 15, 18, 16, 17, 15, 14, 14, 14, 15, NaN, NaN, Na…
## $ Cylinders        <dbl> 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 4, 8, 8, 8, 8, 8, 8, 8…
## $ Displacement     <dbl> 307, 350, 318, 304, 302, 429, 454, 440, 455, 390, 13…
## $ Horsepower       <dbl> 130, 165, 150, 150, 140, 198, 220, 215, 225, 190, 11…
## $ Weight_in_lbs    <dbl> 3504, 3693, 3436, 3433, 3449, 4341, 4354, 4312, 4425…
## $ Acceleration     <dbl> 12.0, 11.5, 11.0, 12.0, 10.5, 10.0, 9.0, 8.5, 10.0, …
## $ Year             <dttm> 1970-01-01, 1970-01-01, 1970-01-01, 1970-01-01, 197…
## $ Origin           <chr> "USA", "USA", "USA", "USA", "USA", "USA", "USA", "US…

Chart

brush <- alt$selection(type = "interval")

chart <- 
  alt$Chart(vega_data$cars())$
  mark_point()$
  encode(
    x = "Horsepower:Q",
    y = "Miles_per_Gallon:Q",
    color = alt$condition(brush, "Cylinders:O", alt$value("grey"))
  )$
  properties(selection = brush)

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)
## Rows: 2,000
## Columns: 4
## $ gender <chr> "M", "M", "M", "M", "M", "M", "M", "M", "M", "M", "M", "M", "M…
## $ height <dbl> 64.33104, 70.90283, 68.16385, 65.53356, 80.29183, 73.71563, 58…
## $ weight <dbl> 125.6792976, 211.4315609, 174.3090368, 63.6559931, -105.182755…
## $ age    <dbl> 55.93944, 38.93365, 51.33421, 48.47302, 48.56442, 53.77342, 53…

Chart

selector <- alt$selection_single(empty = "all", fields = list("gender"))

color_scale <- 
  alt$Scale(
    domain = list("M", "F"),
    range = list('#1FC3AA', '#8624F5')
  )

base <- 
  alt$Chart(source)$
  properties(width = 250, height = 250)$
  add_selection(selector)

points <-
  base$mark_point(filled=TRUE, size=200)$
  encode(
    x = alt$X(
      "mean(height):Q",
      scale = alt$Scale(domain = list(0, 84))
    ),
    y = alt$Y(
      "mean(weight):Q",
      scale = alt$Scale(domain=list(0,250))),
      color = alt$condition(
        selector,
        "gender:N",
        alt$value("lightgray"),
        scale = color_scale
    )
  )$
  interactive()

hists <-
  base$
  mark_bar(opacity = 0.5, thickness = 100)$
  encode(
    x = alt$X(
      "age",
      bin = alt$Bin(step = 5), # step keeps bin size the same
      scale = alt$Scale(domain = list(0, 100))
    ),
    y = alt$Y(
      "count()",
      stack = NULL,
      scale = alt$Scale(domain = list(0, 350))
    ),
    color = alt$Color("gender:N", scale = color_scale)
  )$
  transform_filter(selector)

points | hists

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())
## Rows: 560
## Columns: 3
## $ symbol <chr> "MSFT", "MSFT", "MSFT", "MSFT", "MSFT", "MSFT", "MSFT", "MSFT"…
## $ date   <dttm> 2000-01-01, 2000-02-01, 2000-03-01, 2000-04-01, 2000-05-01, 2…
## $ price  <dbl> 39.81, 36.35, 43.22, 28.37, 25.45, 32.54, 28.40, 28.40, 24.53,…

Chart

highlight <- 
  alt$selection_single(
    on = "mouseover",
    fields = list("symbol"), 
    nearest = TRUE
  )

base <- 
  alt$Chart(vega_data$stocks())$
  encode(
    x = "date:T",
    y = "price:Q",
    color = "symbol:N"
  )

points <- 
  base$mark_circle()$
  encode(
    opacity = alt$value(0)
  )$
  properties(selection = highlight, width = 600)

lines <- 
  base$
  mark_line()$
  encode(
    size = alt$condition(highlight, alt$value(3), alt$value(1))
  )

chart <- (points + lines)

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)
## Rows: 300
## Columns: 3
## $ category <chr> "A", "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, 17, 1…
## $ y        <dbl> 1.37, 0.81, 1.17, 1.80, 2.20, 2.09, 3.60, 3.51, 5.53, 5.47, …

Chart

# Create a selection that chooses the nearest point & selects based on x-value
nearest <- alt$selection(
  type = "single", 
  nearest = TRUE, 
  on = "mouseover",
  fields = list("x"), 
  empty = "none"
)

# The basic line
line <- 
  alt$Chart(data = data)$
  mark_line(interpolate = "basis")$
  encode(
    x = "x:Q",
    y = "y:Q",
    color = "category:N"
  )

# Transparent selectors across the chart. This is what tells us
# the x-value of the cursor
selectors <- 
  alt$Chart(data = data)$
  mark_point()$
  encode(
    x = "x:Q",
    opacity = alt$value(0)
  )$
  properties(selection = nearest)$
  copy()

# Draw points on the line, and highlight based on selection
points <-
  line$
  mark_point()$
  encode(
    opacity = alt$condition(nearest, alt$value(1), alt$value(0))
  )

# Draw text labels near the points, and highlight based on selection
text <- 
  line$
  mark_text(align = "left", dx = 5, dy = -5)$
  encode(
    text = alt$condition(nearest, "y:Q", alt$value(" "))
  )

# Draw a rule at the location of the selection
rules <- 
  alt$Chart(data = data)$
  mark_rule(color = "gray")$
  encode(
    x = "x:Q"
  )$
  transform_filter(nearest$ref())

# Put the five layers into a chart and bind the data
chart <-  
  (line + selectors + points + rules + text)$
  properties( width = 600, height = 300)

chart

Multi-panel Scatter Plot with Linked Brushing

Altair example

Data

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

Chart

source <- vega_data$cars()

brush = alt$selection(type = "interval", resolve = "global")

base = alt$Chart(source)$
  mark_point()$
  encode(
    y = "Miles_per_Gallon",
    color=alt$condition(brush, "Origin", alt$ColorValue("gray"))
  )$
  add_selection(brush)$
  properties(width = 250, height = 250)

base$encode(x = "Horsepower") | base$encode(x = "Acceleration")

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.

Data

movies <- jsonlite::fromJSON(vega_data$movies$url)

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

Chart

movies <- 
  alt$UrlData(
    vega_data$movies$url,
    format = alt$DataFormat(parse = list(`Release Date` = "date"))
  )

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(movies, 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(
      field = "Worldwide_Gross",
      type = "quantitative",
      scale = alt$Scale(domain = c(100000, 10**9), clamp = TRUE)
    ),
    y = alt$Y(field = "IMDB_Rating", type = "quantitative"),
    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)