emehex emehex - 1 month ago 19
R Question

Animate the process of adding layers to a ggplot2 plot

I am starting to get familiar with

gganimate
, but I want to extend my gifs further.

For instance, I can throw a
frame
on one variable in
gganimate
but what if I want to animate the process of adding entirely new layers/geoms/variables?

Here's a standard
gganimate
example:

library(tidyverse)
library(gganimate)

p <- ggplot(mtcars, aes(x = hp, y = mpg, frame = cyl)) +
geom_point()

gg_animate(p)


But what if I want the gif to animate:

# frame 1
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point()

# frame 2
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point(aes(color = factor(cyl)))

# frame 3
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point(aes(color = factor(cyl), size = wt))

# frame 4
ggplot(mtcars, aes(x = hp, y = mpg)) +
geom_point(aes(color = factor(cyl), size = wt)) +
labs(title = "MTCARS")


How might this be accomplished?

Answer

You can manually add a frame aesthetic to each layer, though it will include the legends for all of the frames immediately (Intentionally, I believe, to keep ratios/margins, etc. correct:

saveAnimate <-
  ggplot(mtcars, aes(x = hp, y = mpg)) +
  # frame 1
  geom_point(aes(frame = 1)) +
  # frame 2
  geom_point(aes(color = factor(cyl)
                 , frame = 2)
             ) +
  # frame 3
  geom_point(aes(color = factor(cyl), size = wt
                 , frame = 3)) +
  # frame 4
  geom_point(aes(color = factor(cyl), size = wt
                 , frame = 4)) +
  # I don't think I can add this one
  labs(title = "MTCARS")

gg_animate(saveAnimate)

enter image description here

If you want to be able to add things yourself, and even see how legends, titles, etc. move things around, you may need to step back to a lower-level package, and construct the images yourself. Here, I am using the animation package which allows you to loop through a series of plots, with no limitations (they need not be related at all, so can certainly show things moving the plot area around. Note that I believe this requires ImageMagick to be installed on your computer.

p <- ggplot(mtcars, aes(x = hp, y = mpg))

toSave <- list(
  p + geom_point()
  , p + geom_point(aes(color = factor(cyl)))
  , p + geom_point(aes(color = factor(cyl), size = wt))
  , p + geom_point(aes(color = factor(cyl), size = wt)) +
    labs(title = "MTCARS")
)

library(animation)

saveGIF(
  {lapply(toSave, print)}
  , "animationTest.gif"
 )

enter image description here

Comments