Learning outcomes

  • Create a wide variety of interactive graphics using the plotly and ggiraph packages
  • Learn the basics of shiny
  • Create some animations (not really interactive but sometimes useful)

Part 1: plotly

  • A very rich package, but has the key advantage of one amazing function: ggplotly
library(plotly)
library(palmerpenguins)
p <- ggplot(data = penguins, 
       aes(x = bill_length_mm, y = flipper_length_mm)) + 
  geom_point()
ggplotly(p)

ggplotly plot

Some notes about ggplotly

  • You can use ggplotly with more or less any ggplot that you have created
  • However it doesn’t work for every type of plot, and doesn’t always show exactly what you want in the interactive elements
  • There are extra options that will allow you to adjust what is shown in the tooltip which is the highlighted information when you hover your mouse over the plot

Other ways of using plotly

  • plotly also has its own syntax for creating individual plots
plot_ly(data = penguins, x = ~bill_length_mm, 
        y = ~bill_depth_mm, color = ~sex, 
        type = 'scatter', mode = 'markers')

Boxplots

plot_ly(data = penguins, x = ~species, y = ~bill_depth_mm, type = 'box')

3D plots

plot_ly(data = penguins, x = ~bill_length_mm, 
        y = ~bill_depth_mm, z = ~flipper_length_mm, 
        type = 'scatter3d', mode = 'markers')

Final notes on plotly

  • A very comprehensive support website at https://plotly.com/
  • Versions for all the major data analytics languages
  • A lot of overlap with ggplot2; though has never been quite as popular

Part 2: ggiraph

  • A more direct and controllable way of producing interactive graphs is using ggiraph
  • Just replace geom_X with geom_X_interactive
  • Can then control hover behaviour using tooltip, clicking behaviour using onclick, and the data behaviour using data_id

ggiraph in use

library(ggiraph)
p <- iris %>% mutate(Row.name = 1:n()) %>% 
  ggplot(aes(x = Sepal.Length, y = Sepal.Width, colour = Species,
             tooltip = Row.name, data_id = Species)) +
           geom_point_interactive()
girafe(ggobj = p, width = 10)

Part 3: shiny

  • The shiny package allows you to create beautiful GUIs which open and interact with an internet browser
  • A shiny application involves (at least) two R functions. The first function, called ui.R contains the details of what’s actually going to appear on the webpage. The second, server.R, contains all the details of the R code that needs to be run
  • The website https://shiny.rstudio.com contains some nice examples to get started
  • See http://https://shiny.rstudio.com/gallery/ for some really impressive examples - bear in mind these are not particularly complicated to create

Example Shiny app

Shiny applications not supported in static R Markdown documents

shiny walkthrough

  • Click File > New File > Shiny Web App
  • Choose a name
  • Click Run App

Part 4: animations

The animation package contains functions which will turn static R plots into animations: gifs, html, swf, etc The general framework is:

  1. Set the animation options using ani.options
  2. Put the animation frames for each plot in a loop
  3. Call the ani.pause function to stop the animation running too fast
  4. Wrap the above in a saveGIF/saveSWF/saveHTM function call to output to a file

(It’s a bit like using the pdf and similar commands in base R plotting)

animation example

library(animation)
oopt = ani.options(interval = 0.2, nmax = 100)
for (i in 1:ani.options("nmax")) {
    plot(density(rnorm(10*i)),
         main = 10*i)
    ani.pause()
}

ggplot animations with gganimate

Has special function called transition_state which works a little bit like facet_wrap but overlays the facets

library(gganimate)
library(gifski)
p <- ggplot(data = penguins, aes(x = flipper_length_mm, 
                                 y = body_mass_g)) +
  geom_point() +
  # Add an animation of the penguins' species over time
  transition_states(species, transition_length = 2, 
                    state_length = 1) +
  # Add a label for the current species
  labs(title = "Penguin species: {closest_state}")
animate(p, renderer = gifski_renderer())

More gganimate

library(gapminder)
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, 
                           label = country,
                           size = pop, 
                           colour = country)) +
  geom_point(alpha = 0.7, show.legend = FALSE) +
  #geom_text() + 
  scale_colour_manual(values = country_colors) +
  scale_size(range = c(2, 12)) +
  scale_x_log10() +
  facet_wrap(~continent) +
  labs(title = 'Year: {frame_time}', x = 'GDP per capita', y = 'life expectancy') +
  # Here comes the gganimate specific bits
  transition_time(year) +
  ease_aes('linear')
animate(p, renderer = gifski_renderer())

Final words on gganimate

  • Great manual/website at https://gganimate.com
  • Lots of different transition functions for all kinds of different functionality
  • Loads of other different functions for behaviour of background data, movements between frames, scale changes, aesthetic changes, etc
  • Can output the files in a gif or other movie file using the animate function

Summary

  • plotly is the way to start if you just want to create a simple animation from a ggplot. If you want more control use ggiraph
  • Use shiny for full dashboard control of plots and any other R feature. A whole other course required to understand this fully
  • gganimate a great package for creating animations (though also see plotly which can add a play button)