One of the main advantages to use the altair package is the fact that supports the generation of interactive graphics. The code required for adding a simple interaction is relatively short.

Tooltip

A tooltip can be added to the plot using tooltip() inside encode(). For one variable displayed in the tooltip we can use:

...
tooltip = "Variable_1:T"
...

and for more than one variable, we can use the R function list() or c() as illustrated below:

...
tooltip = c("Variable_1:T", "Variable_2:T")
...

Mind that if we are importing the data from a url directly in the plot specification, we may need to specify the field type. As shown above we may use “T” for the type, where “T” may be for instance O for orninal, Q for quantitative or N for nominal.

Exercise - Add a tooltip in the heatmap we created in the previous section, to get the graph illustrated above.

Zooming and Panning

We illustrate two ways of making a graph zoomable and pannable. The first one is by adding the intreactive() attribute, as illustrated below:

chart = alt$Chart(data_source_subset)$
   .....
   $interactive()

A second option is to specify the selection outside the plot code and then use it inside the add_selection attribute in the chart code. The second option is an interval selection using a scale binding. For more information on selection types supported in altair you can refer to altair.selection_interval reference

selection = alt$selection_interval(bind='scales')

chart = alt$Chart(data_source_subset)$
.....
$add_selection(
    selection
  )

Exercise - Make the time series plot of all natural distasters interactive, to get the graph illustrated above. Use both ways of making it zoomable and pannable.