Module #13 - Animation in R

This module's assignment called to explore using animation in R. While the animation package by Yihui Xie appears to be robust in its functionality, I was able to find a similar package, gganimate, which specializes in transitions and animations with ggplot2, my most frequently used plotting package.

The animation package seems more lightweight, with 9 less 'depends' than gganimate. However, I am pleased with the results of gganimate and look forward to using it in the future. I was also impressed with how easily the GIF files could be generated.

I was personally surprised to see how such dynamic output could come from just 40 lines of code!

Link to GitHub R Script


mtcars plot


I am pleased with how the below plot groups the transitions based on the number of cylinders that is also displayed in the subtitle as the animation progresses. The animation used here is a neat way to display groups of plot figures without faceting:




iris plot


This plot is more revealing of the relationship between the two observed variables. The data lends itself well to this type of animation becaused the data is strongly segmented by the Species variable:



  ############################################################################
  # ----- ------ ------ ----- MOD13: Animation in R ----- ------ ------ -----
  ############################################################################
  #' ---
  #' title:   "MOD13: Animation in R"
  #' author:  "Kevin Hitt"
  #' date:    "Due: April 20th, 2020"
  #' ---

  # Load packages
  library(ggplot2)
  library(gganimate)
  library(ggthemes)

  # Animation plot 1
  plot_car <- ggplot(mtcars, aes(x = mpg, y = hp)) +
    geom_point(aes(color = as.factor(cyl), group = 1L)) +
    transition_states(cyl,
                      transition_length = 2,
                      state_length = 1) +
    ease_aes("cubic-in-out") +
    ggtitle("MPG vs. Horsepower",
            subtitle = "Now showing {closest_state} cylinders") +
    labs(fill="# of Cylinders") +
    theme_linedraw()

  # Animation plot 2
  plot_iris <- ggplot(iris, aes(x = Petal.Width, y = Petal.Length)) +
    geom_point(aes(color = Species, group = 1L)) +
    transition_states(Species,
                      transition_length = 2,
                      state_length = 1) +
    ease_aes("cubic-in-out") +
    ggtitle("Petal Width vs. Petal Length",
            subtitle = "Now showing {closest_state} species") +
    theme_linedraw()

  # Export to GIF files
  anim_save("car.gif", plot_car)
  anim_save("iris.gif", plot_iris)