# Downloading packages -------------------------------------------------------
- Downloading plotly from https://packagemanager.posit.co/cran/__linux__/noble/latest ... OK [3.7 Mb in 0.37s]
Successfully downloaded 1 package in 1.8 seconds.

The following package(s) will be installed:
- plotly [4.11.0]
These packages will be installed into "~/work/dvac-SSA/dvac-SSA/renv/library/linux-ubuntu-noble/R-4.4/x86_64-pc-linux-gnu".

# Installing packages --------------------------------------------------------
- Installing plotly ...                         OK [installed binary and cached in 0.89s]
Successfully installed 1 package in 0.96 seconds.
# Downloading packages -------------------------------------------------------
- Downloading gapminder from https://packagemanager.posit.co/cran/__linux__/noble/latest ... OK [2 Mb in 1.1s]
Successfully downloaded 1 package in 1.3 seconds.

The following package(s) will be installed:
- gapminder [1.0.1]
These packages will be installed into "~/work/dvac-SSA/dvac-SSA/renv/library/linux-ubuntu-noble/R-4.4/x86_64-pc-linux-gnu".

# Installing packages --------------------------------------------------------
- Installing gapminder ...                      OK [installed binary and cached in 0.41s]
Successfully installed 1 package in 0.44 seconds.


ETX2250/ETF5922

Interactivity and Animation

Lecturer: Kate Saunders

Department of Econometrics and Business Statistics



Learning Objectives

We’ve covered the basics of static visualisations.

It’s time to learn about interactive and animated visualisations.

Today’s class

  • Discover the graphical principles behind interactive visualisations

  • Learn how to take a ggplot and make it interactive with a few simple lines of code

  • Learn about the grammar of animated graphics

  • Learn how to create our own animated visualisations in R

Interactive Visualisation

Interactive Visualisation

Definition

Data visualisation that is directly manipulated and explored through user input.

Why

  • Better connect people and data - Tailor the messages

  • Make the system playful - Help people explore the data

  • Prompt self-reflection - If I do this, then that happens

  • Personalise the view - Audience can chose how they interact with the visual

  • Reduce cognitive load - Allows for different display of complex data

Human Computer Interaction

What?

Open-ended dialogue between the user and the computer

Enabling the audience to co-author the narrative, i.e. decide what to display.

The shared narrative is created through through user interactions and user inputs

User Interactions

Image from Spencer (2022, Feb. 17). Data in Wonderland. Retrieved from https://ssp3nc3r.github.io/data_in_wonderland

User Inputs

Image from Spencer (2022, Feb. 17). Data in Wonderland. Retrieved from https://ssp3nc3r.github.io/data_in_wonderland

Quality Criteria

Expressiveness (Mandatory Condition)

An interactive visual representation is expressive if it allows the user to carry out the actions needed to acquire the desired information in the data.

Effectiveness (Goal-Oriented Condition)

A measure of how well the user can convey an interaction intent to the computer.

Efficiency (Desired Condition)

The balance between benefits and costs of using interactive visualisation.

Example: Global Temperature

https://climate.nasa.gov/vital-signs/global-temperature/

Your turn

Your turn

Follow the link on the previous slide to the interaction visualisation.

  • What sort of user interactions are available?

  • Can you interact with the visualisation in the way you want?

  • Do the interactive elements work effectively?

  • Does adding the interactivity help you to understand this visualisation better?

How do we create one?

What is plotly?

Plotly

  • ploty is an R library you can use to make interactive, publication-quality graphs.

  • It is free and open source.

Let’s start by installing the plotly package.

install.packages("plotly")

How to create interactive visualisation?

  • First, we need the ggplot object
  • Then using ggplotly() function we can convert the ggplot object into interactive graphic

User inputs to ggplotly()

See ?ggplotly

  • p: a ggplot object
  • tooltip: A character vector specifying which aesthetic mappings to show in the tooltip.

Example

First

Create a ggplot object

library(gapminder)

options(scipen = 999)

gapminder_plot <- gapminder |>
  filter(year == 2007) |> 
  ggplot(aes(x = gdpPercap, y = lifeExp, color = continent)) +
  geom_point() +
  scale_x_log10() +
  labs(title = "Life expectency vs GDP per capita by continent in 2007",
       x = "GDP per capita",
       y = "Life expectency") +
  theme_bw() +
  theme(legend.title = element_blank()) +
  colorblindr::scale_color_OkabeIto()

gapminder_plot

Static Plot

Let’s make it interactive

Next

Put the ggplot object inside the ggplotly function.

ggplotly(gapminder_plot,
         tooltip = "all")

Interactive Plot

Tooltip

Tooltip

  • A tooltip is an element that displays information when we hover over the data.

  • Also known as an info tip

  • By default, all aes mapping variables are shown.

  • What if we want to only display some of the mappings?

# One variable
ggplotly(gapminder_plot,
         tooltip = "x")

# More than one variable
ggplotly(gapminder_plot,
         tooltip = c("x", "y"))

Tooltip

Extra information

  • What if the user is interested in information like country?

  • Remember, the tooltip displays information from the mapping argument

Tooltip

gapminder_plot2 <- gapminder |>
  filter(year == 2007) |> 
  ggplot(aes(x = gdpPercap, y = lifeExp, color = continent, 
             country = country)) +
  geom_point() +
  scale_x_log10() +
  labs(title = "Life expectency vs GDP per capita by continent in 2007",
       x = "GDP per capita",
       y = "Life expectency") +
  theme_bw() +
  theme(legend.title = element_blank()) +
  colorblindr::scale_color_OkabeIto()

ggplotly(gapminder_plot2,
         tooltip = "country")

Tooltip

Your turn

Your turn

  • Load in the gapminder data.
  • Create an interactive line plot showing how the European GDP changes over time.
  • Have the tooltip display country, year, and gdpPercap information.

Animation

Animation

Why?

  • Add another dimension.
  • Provides a more compact delivery of information.
  • Allows for guided exploration of data, great for talks.
  • Capture the audience’s attention.

Animation

Considerations for making an effective animation.

Principles

  • Pace: speed of animation
    • Quick animations may be hard to follow. Slow animations are boring and tedious.
  • Perplexity: amount of information
    • It is easy for animations to be overwhelming and confusing. Multiple simple animations can be easier to digest.
  • Purpose: Usefulness of using animation
    • Is animation needed? Does it provide additional value?

Example

How do we create animated plot?

gganimate

  • An extension to the ggplot2 package, designed to create animation and interactive visualisation.
  • It works by adding animation-specific layers

Let’s start by installing a gganimate package

install.packages("gganimate")

gganimate

Just like in ggplot where there is a grammar of graphics.

In gganimate there is a grammar of animation.

This grammar controls movement with:

  • Transitions (main focus for today)
  • Views
  • Shadows
  • Entrances/Exits
  • Easing

You can see more here.

Transitions

Specify how the data changes through the animation

Transition functions

  • transition_time()
    • Transition the plot through time
  • transition_reveal()
    • Gradually extend the data used to reveal more information.
  • transition_layers()
    • Animate the addition of layers to the plot. Can also remove layers.

Let’s see these in action.

transition_time()

ggplot(gapminder) +
  geom_point(aes(x = gdpPercap, y = lifeExp, size = pop,
                 color = continent)) +
  scale_x_log10() +
  theme_bw() +
  transition_time(year)

transition_reveal()

gapminder |>
  filter(country == "Australia") |>
  ggplot(aes(x = year, y = gdpPercap)) +
  geom_line() +
  geom_point() +
  theme_bw() +
  transition_reveal(year)

transition_layers()

ggplot(data = gapminder,
         aes(x = gdpPercap, y = lifeExp)) +
  geom_point() +
  geom_smooth() +
  scale_x_log10() +
  transition_layers() +
  enter_fade() 

Our Waffle: Example

library(ggthemes)
library(waffle)

people_data_1 = data.frame(
  Person = c("Maths", "Math Artists", "Math Artists that Play Poker"),
  count = c(20*20, 0, 0))

people_data_2 = data.frame(
  Person = c("Maths", "Math Artists", "Math Artists that Play Poker"),
  count = c(20*20 - 10, 10, 0))

people_data_3 = data.frame(
  Person = c("Maths", "Math Artists", "Math Artists that Play Poker"),
  count = c(20*20 - 10, 7, 3))

ggplot() +
  geom_waffle(data = people_data_1, aes(fill = Person, values = count),
              n_rows = 20, size = 0.5, color = "white") +
  geom_waffle(data = people_data_2, aes(fill = Person, values = count),
              n_rows = 20, size = 0.5, color = "white") +
  geom_waffle(data = people_data_3, aes(fill = Person, values = count),
              n_rows = 20, size = 0.5, color = "white") +
  scale_fill_colorblind() +
  coord_fixed() +
  theme_minimal() +
  labs(title = "One Million Majors in Maths") +
  theme(axis.text = element_blank(),
        legend.position = "bottom",
        plot.title = element_text(size = 20),
        legend.text = element_text(size = 10)) +
  transition_layers() +
  enter_fade() +
  enter_grow()

Your turn

Your turn

  • Copy the code

  • Complete the code to create an animated visualisation that reveals the line plot

stock <- read_csv("data/big-tech-stock-price.csv") |>
  mutate(date = ymd(date)) |>
  filter(stock_symbol == "AAPL",
         year(date) > 2016)

ggplot(stock) +
  geom_line(aes(x = date, y = close)) +
  labs(x = "Date", y = "Closing price",
       title = "Apple Inc stock price during the pandemic") +
  theme_bw() +
  theme(
    aspect.ratio = 0.5,
    plot.title = element_text(size = 16, face = "bold", hjust = 0.5)
    ) +
  ???

Wrap Up

Summary

Summary

  • Interactivity and animation are great tools to turn your analysis into more effective, digital story telling.

  • Interactivity and animation are also a great way to provide additional detail

  • For interactivity remember: expressiveness, effectiveness and efficiency.

  • For both interactivity and animation you must always still consider your audience, message and medium

Promise

Promise

I solemnly swear that:

  • I will only use interactive graphics when it is appropriate for audience, message and medium.

  • I promise that I won’t just add them to everything just because they are cool!

Down the Rabbit Hole

Other tools for interactive graphics

If you’d like to continue your adventures in Wonderland:

A Comment on the Unit

It’s not always obvious what goes on behind the scenes.

What’s been changing

Last year I redeveloped this entire unit, and based on the feedback this is what I’ve worked on this year.

  • Improved and extended all the in class consolidation exercises - Your turns

  • Overhauled all the quizzes.
    Now you get multiple attempts and they recap all the core concepts

  • Updated the data in Workshop 6 and replaced the example

  • Rewrote the Workshop 9 Material: Building the Data Narrative so we have a smooter introduction to Quarto and closeread

  • Updated all the rubrics so they are clearer and added the learning objectives

  • Encouraged and expanded the use of AI in this unit

Solutions

Solution: plotly

Solution

stock <- read_csv("data/big-tech-stock-price.csv") |>
  mutate(date = ymd(date)) |>
  filter(stock_symbol == "AAPL",
         year(date) > 2016)

ggplot(stock) +
  geom_line(aes(x = date, y = close)) +
  labs(x = "Date", y = "Closing price",
       title = "Apple Inc stock price during the pandemic") +
  theme_bw() +
  theme(
    aspect.ratio = 0.5,
    plot.title = element_text(size = 16, face = "bold", hjust = 0.5)
    ) +
  transition_reveal(date)