Black Lives Matter. Please consider donating to Black Girls Code today.

Intro to Animations in ggplot2

How to create animations in ggplot2 with Plotly.


New to Plotly?

Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.

Frames

Now, along with data and layout, frames is added to the keys that figure allows. Your frames key points to a list of figures, each of which will be cycled through upon instantiation of the plot.

Basic Example

library(plotly)

df <- data.frame(
  x = c(1,2,3,4), 
  y = c(1,2,3,4), 
  f = c(1,2,3,4)
)

p <- ggplot(df, aes(x, y)) +
    geom_point(aes(frame = f))

fig <- ggplotly(p)

fig

Mulitple Trace Animations

library(plotly)
library(gapminder)


p <- ggplot(gapminder, aes(gdpPercap, lifeExp, color = continent)) +
  geom_point(aes(size = pop, frame = year, ids = country)) +
  scale_x_log10()

fig <- ggplotly(p)

fig

Add Animation Options

library(plotly)

fig <- fig %>% 
  animation_opts(
    1000, easing = "elastic", redraw = FALSE
  )

fig

Add Button Options

library(plotly)

fig <- fig %>% 
  animation_button(
    x = 1, xanchor = "right", y = 0, yanchor = "bottom"
  )

fig