When you generate a series of plots in a code chunk, you can combine them into an animation. It is easy to do so if the output format is HTML—you only need to install the gifski package (Ooms, Kornel Lesiński, and Authors of the dependency Rust crates 2023) and set the chunk option animation.hook = "gifski". Figure 4.3 shows a simple “Pac-man” animation created from the code chunk below:

  1. ```{r, animation.hook="gifski"}
  2. for (i in 1:2) {
  3. pie(c(i %% 2, 6), col = c('red', 'yellow'), labels = NA)
  4. }
  5. ```

Image 1: A Pac-man animation.

FIGURE 4.3: A Pac-man animation.

The image format of the animation is GIF, which works well for HTML output, but it is not straightforward to support GIF in LaTeX. That is why you only see two static image frames in Figure 4.3 if you are reading the PDF or printed version of this book. If you read the online version of this book, you will see the actual animation.

Animations can work in PDF, but there are two prerequisites. First, you have to load the LaTeX package animate (see Section 6.4 for how). Second, you can only use Acrobat Reader to view the animation. Then the chunk option fig.show = "animate" will use the animate package to create the animation. Below is an example:

  1. ---
  2. title: Animations in PDF
  3. output:
  4. pdf_document:
  5. extra_dependencies: animate
  6. ---
  7. The animation below can only be viewed in Acrobat Reader.
  8. ```{r, fig.show='animate'}
  9. for (i in 1:2) {
  10. pie(c(i %% 2, 6), col = c('red', 'yellow'), labels = NA)
  11. }
  12. ```

The time interval between image frames in the animation can be set by the chunk option interval. By default, interval = 1 (i.e., one second).

The R package animation (Xie 2021) contains several animation examples to illustrate methods and ideas in statistical computing. The gganimate package (Pedersen and Robinson 2024) allows us to create smooth animations based on ggplot2 (Wickham, Chang, et al. 2024). Both packages work with R Markdown.

References

Ooms, Jeroen, Kornel Lesiński, and Authors of the dependency Rust crates. 2023. Gifski: Highest Quality GIF Encoder. https://r-rust.r-universe.dev/gifski.

Pedersen, Thomas Lin, and David Robinson. 2024. Gganimate: A Grammar of Animated Graphics. https://gganimate.com.

Wickham, Hadley, Winston Chang, Lionel Henry, Thomas Lin Pedersen, Kohske Takahashi, Claus Wilke, Kara Woo, Hiroaki Yutani, Dewey Dunnington, and Teun van den Brand. 2024. Ggplot2: Create Elegant Data Visualisations Using the Grammar of Graphics. https://ggplot2.tidyverse.org.

———. 2021. Animation: A Gallery of Animations in Statistics and Utilities to Create Animations. https://yihui.org/animation/.