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)
library(ggplot2)
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))
ggplotly(p)
Mulitple Trace Animations
library(plotly)
library(ggplot2)
library(gapminder)
p <- ggplot(gapminder, aes(gdpPercap, lifeExp, color = continent)) +
geom_point(aes(size = pop, frame = year, ids = country)) +
scale_x_log10()
ggplotly(p)
Add Animation Options
To add options to the plot, first convert ggplot2 plot to Plotly variable with ggplotly()
and then, add options to that variable.
library(plotly)
library(ggplot2)
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 <- fig %>%
animation_opts(
1000, easing = "elastic", redraw = FALSE
)
fig
Add Button Options
library(plotly)
library(ggplot2)
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 <- fig %>%
animation_opts(
1000, easing = "elastic", redraw = FALSE
)
fig <- fig %>%
animation_button(
x = 1, xanchor = "right", y = 0, yanchor = "bottom"
)
fig