Site icon texblog

Making animations in R for LaTeX

The R package animation has a function saveLatex() which creates a tex document (and compiles it) with the animation created by your R code. It essentially produces the individual image files and a tex file that uses the LaTeX package animate to create the animation in the pdf. Here is an example of an R code that creates a tex document.

library(datasets)
library(dplyr)
library(animation)
data(airquality)

months <- 5:9

saveLatex(expr=c(for (i in months) {
  data <- filter(airquality, Month == i)
  plot(x = data$Temp, y = data$Ozone)
}), interval=4, img.name = "Rplot", latex.filename="TexFromR.tex", outdir=getwd(), documentclass="article")

It saves 5 image files Rplot1.png … Rplot5.png (there are 5 different months in the airquality dataset) and the TexFromR.tex file, as well as compiles the tex file into a pdf. The TexFromR.tex file will then look like this.

\documentclass{article}
    \usepackage{animate}
    \begin{document}
    \begin{figure}
    \begin{center}
    \animategraphics[controls,width=\linewidth]{0.25}{Rplot}{1}{5}
    \end{center}
    \end{figure}
    \end{document}

The corresponding pdf with the animation can be viewed here. The animations are unfortunately only supported by some pdf readers (AcrobatReader, PDF-XChange, acroread, and Foxit Reader). For visualization here is also an animated screen capture.

There are many options that you can use in saveLatex() to customize the tex output. Among them is documentclass which defines the LaTeX document class and if set to NULL will not produce a complete LaTeX document, but only the code to generate the PDF animation will be printed in the console. This code can then be used in your tex file with the LaTeX package animate.

Exit mobile version