We have seen how to select datapoints with brushing and linking. We are now looking at how to select datapoints based on a variable, using widgets. In the example below, we make a layered time series chart in which we can select the natural disaster to be displayed form a dropdown list. In the default view, all time series are displayed.

There are four steps to make this plot in altair R.

  • First, we make a list of the elements that will be included in the dropdown selection, using conventional R code. We make sure that the elements of the list match the names of the variable we want to filter.
  • Then, we create the chart, in the same way as we would make it if we have already filtered the data on one of the options included in the list above.
  • In the third step, we make a dynamic query for the dropdown menu. To do so, we create a single element selection entities_select. We specify the name of the field we want to filter in fields = list(). We use the binding_select to specify the input options for the dynamic query. Last, we give a name for the widget.
  • Finally, we modify the chart of step 2 by including the single selection we made in the previous step. We also include in the final chart a filter transform based on the dynamic query.
# step 1
entities = list("Drought", "Earthquake", "Epidemic", "Extreme temperature", "Extreme weather", "Flood", "Landslide", "Mass movement (dry)", "Volcanic activity", "Wildfire")
  
# step 2
chart_a = alt$Chart(data_source_modified_subset)$
  mark_line()$
  encode(
    x = "Year:O",
    y = "Deaths:Q",
    tooltip = c("Year:N","Deaths:Q")
  )$
  properties(
    height = 300,
    width = 700
  )

chart_b = chart_a$mark_circle(size = 50)$encode(x = "Year:O", y = "Deaths:Q", color = "Missing:N")

chart = chart_b + chart_a

# step 3
entities_select = alt$selection_single(
    fields = list("Entity"), 
    bind = alt$binding_select(options = entities),
    name = "Filter"
  )

# step 4
chart_filter_entities = chart$
  add_selection(entities_select)$
  transform_filter(entities_select)


For more information you may refer to the reference for selection_single and to the guide on binding The vega-lite documentation for selections may also be useful.


Exercise - Make a normalized stacked area chart of Deaths versus Year for Epidemic, Extreme temperature, Extreme weather and Flood. Include a radio button that allow you to highlight one type of disaster at a time. The end result should look like the chart below. Hint: Use binding_radio.