Skip to content

Instantly share code, notes, and snippets.

@jonocarroll
Created October 8, 2018 22:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonocarroll/3ceb7fe9c48cd1cebc94a0c10653fcb6 to your computer and use it in GitHub Desktop.
Save jonocarroll/3ceb7fe9c48cd1cebc94a0c10653fcb6 to your computer and use it in GitHub Desktop.
PDF Animations in RMarkdown
---
title: "Test Animation in PDF"
author: "Jonathan Carroll"
date: "09/10/2018"
output: pdf_document
header-includes:
- \usepackage[final,autoplay]{animate}
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```
## Create individual frames
```{r}
library(ggplot2)
files <- path.expand(file.path("~", "Documents", "Sandbox", "PDFanimation", "indiv_plots"))
unlink(files, recursive = TRUE)
dir.create(files)
set.seed(1)
n <- 1e4
for (frame in 1:20) {
d <- data.frame(x = rnorm(n, mean = frame, sd = frame/10)
)
g <- ggplot(d) + geom_density(aes(x)) + coord_cartesian(xlim = c(0, 20), ylim = c(0, 1))
suppressMessages({
ggsave(g, filename = file.path(files, paste0("frame_", frame, ".jpg")))
})
}
```
## LaTeX Animation
If you have lots of individual files, you can animate them with LaTeX. The code
to produce this is from $LaTeX$. The YAML header requires
```{latex, eval = FALSE}
header-includes:
- \usepackage[final,autoplay]{animate}
```
and the actual animation is created with
```{latex, eval = FALSE}
\animategraphics[width=0.8\textwidth,loop]{10}{`r paste0(files, "/frame_")`}{1}{20}
```
$\animategraphics[width=0.8\textwidth,loop]{10}{`r paste0(files, "/frame_")`}{1}{20}$
which will be viewable from Adobe Acrobat (at least).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment