**"R" you ready?**, and kindly contributed to R-bloggers)

The first week of April I attended an excellent workshop on biplots held by Michael Greenacre and Oleg Nenadić at the Gesis Institute in Cologne, Germany. Throughout his presentations, Michael used animations to visualize the concepts he was explaining. He also included animations in some of his papers. This inspired me to do this post in which I will show how to use LaTex, R and Sweave to include animations in a PDF document. Here is the PDF document we will create (on MacOS the standard PDF viewer may not be able to play the animations, but Adobe Reader will). For this post some basic knowledge about Sweave is assumed.

First, let’s create a simple animation in R. I will use a neat example Oleg used during the biplot workshop: Pacman eating. Herefore we need a pacman. We use a pie chart to construct him

pie(c(.1, .9, .1) # a pie chart pie(c(.1, .9, .1), # a pie chart col=c("white", "yellow", "white"), # resembling pac man border=NA, labels=NA) points(.3,.4, pch=16, cex=4) # adding an eye

Next, we will produce a series of pictures of Pacman by varying a parameter that specifies how far he opens his mouth. Here, all the single pics are saved in one PDF file, each as one page.

p <- seq(0.999, .9, len=10) # parameters for opening mouth p <- c(rev(p), p) # add reversed parameters pdf(file="pacman.pdf") # open pdf device for (i in 1:length(p)){ pie(c(1-p[i], p[i], 1-p[i]), # pac man like pie chart col=c("white", "yellow", "white"), border=NA, labels=NA) points(.3,.4, pch=16, cex=4) # add the eye } dev.off() # close pdf device

Now, each page of the PDF file contains a single frame of an animation. To include it as an animation in LaTex the `animate` package can be used. Here is the whole code with the Pacman frames being rendered and included via LaTex.

\documentclass{article} \usepackage{animate} % for animated figures \title{Animations in \LaTeX{} via {\sf R} and Sweave} \author{Mark Heckmann} \begin{document} \maketitle <<echo=false, results=hide>>= p <- seq(0.999, .9, len=10) # parameters for opening mouth p <- c(rev(p), p) # add reversed parameters pdf(file="pacman.pdf") # open pdf device for (i in 1:length(p)){ pie(c(1-p[i], p[i], 1-p[i]), # pac man like pie chart col=c("white", "yellow", "white"), border=NA, labels=NA) points(.3,.4, pch=16, cex=4) # add the eye } dev.off() # close pdf device 4 \begin{center} \animategraphics[loop, width=.7\linewidth]{12}{pacman}{}{}\\ \vspace{-5mm} Click me! \end{center} \end{document}

If you click on Pacman in the PDF file, he will start eating. Now let’s create another example and add a panel to control the animation in the PDF. To add controls to the animation use the controls tag in the `\animategraphics` command. In the example several values from a uniform distribution are sampled and their mean is calculated. The mean values are plotted in a histogram. The example is supposed to demonstrate the central limit theorem.

<<eval=true, echo=false, results=hide>>= pdf("limit.pdf") # open pdf device msam <- NA # set up empty vector ns <- 3 # sample size for(i in 1:500){ sam <- runif(ns) * 10 # draw sample msam[i] <- mean(sam) # save mean of sample h <- hist(msam, breaks=seq(0,10, len=50), # histogram of all means xlim=c(0,10), col=grey(.9), xlab="", main="", border="white", las=1) points(sam, rep(max(h$count), length(sam)), pch=16, col=grey(.2)) # add sampled values points(msam[i], max(h$count), # add sample mean value col="red", pch=15) text(10, max(h$count), paste("sample no", i)) hist(msam[i], breaks=seq(0,10, len=50), # ovelay sample mean xlim=c(0,10), col="red", add=T, # in histogram xlab="", border="white", las=1) } dev.off() # close pdf device 4

As a last example we will include a 3D animation created using `rgl`. Herefore we will create random points and rotate them about the x-axis and then about the y-axis.

<<echo=f, results=hide>>= library(rgl) # load rgl library x <- matrix(rnorm(30), ncol=3) # make random points plot3d(x) # plot points in 3d device par3d(params=list( windowRect=c(100,100,600,600))) # enlarge 3d device view3d( theta = 0, phi = 0) # change 3d view angle M <- par3d("userMatrix") # get current position matrix M1 <- rotate3d(M, .9*pi/2, 1, 0, 0) M2 <- rotate3d(M1, pi/2, 0, 0, 1) movie3d(par3dinterp( userMatrix=list(M, M1, M2, M1, M), method="linear"), duration=4, convert=F, clean=F, dir="pics") # save frames in pics folder 4

The inclusion into LaTex works a bit different this time. This time we do not include the single pages from a PDF as frames but we use singe .png pics that have been geberetaed by `movid3d()`. The default file name for the frames generated by movie3d is “movie” plus the frame number.

\begin{center} \animategraphics[controls, loop, width=.7\linewidth]{6} {pics/movie}{001}{040} \end{center}

Here is the whole code for the PDF containing the three animations ready to be Sweaved (make sure to set the directory in the last animation correctly).

**leave a comment**for the author, please follow the link and comment on their blog:

**"R" you ready?**.

R-bloggers.com offers

**daily e-mail updates**about R news and tutorials on topics such as: visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...