Animated plots in R and LaTeX

Published on 13 October 2010

I like to use ani­mated plots in my talks on func­tional time series, partly because it is the only way to really see what is going on with changes in the shapes of curves over time, and also because audi­ences love them! Here is how it is done.

For LaTeX, you need to cre­ate every frame as a sep­a­rate graph­ics file. Here is an exam­ple. First the R code:

library(demography)
nyears <- length(fr.mort$year)
for(i in 1:nyears)
{
    pdf(paste("frmale",i,".pdf",sep=""),height=4,width=6.5)
    x <- fr.mort
    if(i<nyears)
        x$rate$male[,(i+1):nyears] <- NA
    plot(x,series="male",ylim=c(-9.5,1.5),
        main=paste("French: male mortality (",fr.mort$year[1]-1+i,")",sep=""))
    if(i>1)
        x$rate$male[,1:(i-1)] <- NA
    lines(x,series='male',lwd=2,col=1)
    dev.off()
}

This cre­ates a series of pdf files in the figs direc­tory, named frmale1.pdf, …, frmale191.pdf.  In the LaTeX file, you need to load the ani­mate pack­age. Then the fol­low­ing com­mand will do the magic:

\centerline{\animategraphics[controls,buttonsize=0.3cm,width=12.5cm]
    {6}{"frmale"}{1}{191}}

(Put it all on one line with­out the spaces.) This is how the graph on slide 2 of this pre­sen­ta­tion was produced.

For web usage, it is bet­ter to pro­duce an ani­mated gif ver­sion in R:

library(animation)
library(demography)
nyears <- length(fr.mort$year)
makeplot <- function(){
for(i in 1:nyears)
{
    x <- fr.mort
    if(i<nyears)
        x$rate$male[,(i+1):nyears] <- NA
    plot(x,series="male",ylim=c(-9.5,1.5),
        main=paste("French: male mortality (",fr.mort$year[1]-1+i,")",sep=""))
    if(i>1)
        x$rate$male[,1:(i-1)] <- NA
    lines(x,series='male',lwd=2,col=1)
}
}
oopt = ani.options(interval = 0, nmax = nyears)
saveMovie(makeplot(),interval = 0.1, width = 580, height = 400)
ani.options(oopt)

Click the graph below for the ani­mated version.

For an expla­na­tion of the colours, see my rain­bow plot paper.

The ani­ma­tion pack­age for R also allows graph­ics to be saved in other for­mats. SeeAni­Wiki for some exam­ples of ani­ma­tions.