### Using R, Sweave and Latex to integrate animations into PDFs

18Apr11 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>>=
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).

#### 7 Responses to “Using R, Sweave and Latex to integrate animations into PDFs”

1. 1 jens

Thanks. This so saved my day. Now I’m thinking about the hundred nifty things I could do with this (and drive reviewers to the brink of insanity, along the way)

2. 2 markheckmann

Right! I was also wondering how many journals would accept such a thing…

3. 3 Mathieu

Hi,

Any idea if a free* pdf reader can read these animated pdfs? xpdf is not capable of it, evince 2.32 is slightly better as it recognize some links, but cannot show the animations…

I find it a bit frustrating to prepare documents in a free way, and being forced to use Adobe Reader to correctly read them…

Thx,
Mathieu.

* As in free speech, not as in free bear, i.e. Adobe Reader is not a good option for me…

4. 4 markheckmann

Hi,
I do not know if there are other PDF readers that are capable to display the animations.
If you happen to find one, please let me know! :)
Mark

5. 5 2noob2banoob

According to http://stackoverflow.com/questions/2428372/insert-video-clip-in-a-lyx-presentation-and-play-it-in-gnu-linux some animation playback is possible in Okular. However you have to make a real video file (animations created in the way this page describes don’t work) and include it with the multimedia package; also a lot of options work buggy or not at all in Okular.

6. Hi all,

The package kml3d provide a function that generate a graphical 3D representation of joint longitudinal data. Here is the code :

R> #####################
R> ###### Using R ######
R> #####################

R> ### Artificial example of joitn trajectories
R> myData kml3d(myData)

R> ### Creation of the scene
R> scene ### Export in ‘.asy’ file
R> saveTrianglesAsASY(scene)

R> ### Creation of the LaTeX main document
R> makeLatexFile()

Cons> ##########################
Cons> ######## In a console #######
Cons> ##########################

Cons> ### Creation of a ‘.prc’ file using asymptote.:
Cons> ‘asy -inlineimage -tex pdflatex scene.asy’

Cons> ### Creation of the ‘.pdf’
Cons> pdfLatex main.tex

Here is an example:

Click to access fig4.pdf