A blog by Rob J Hyndman 

Twitter Gplus RSS

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. See Ani­Wiki for some exam­ples of ani­ma­tions.


Related Posts:


 
17 Comments  comments 
  • Nam Van

    Thanks for very impres­sive pre­sen­ta­tion. I am new be, so i would like to ask you how to pre­pare the data matrix? as i under­stand you ploted two col­umn, “male” and “rate”, where the vari­able “year” appear?

    • http://robjhyndman.com Rob J Hyndman

      For these graphs I used the facil­i­ties in the demog­ra­phy pack­age. But you can do it gen­er­ally using the mat­plot() and mat­lines() com­mands. Then matplot(age,rates,type=“l”) where rates is a matrix with nrows=length(age).

  • Nam Van

    Thank you very much for your quick and help­ful reply.

  • Nam Van

    In my case, i want to ana­lyze many curves with some neg­a­tive val­ues in the curve, and hor­i­zon­tal axis is fre­quency (in a log scale). It can be applied with FDA? and how? Thank you!!!

    • http://robjhyndman.com Rob J Hyndman

      It sounds like a stan­dard func­tional data prob­lem. You should read the books by Ram­say and Sil­ver­man for an introduction.

  • Nam Van

    - I try your R code with pack­age “demoga­phy” but error appears as“Error in plot.xy(xy.coords(x, y), type = type, …) :
    plot.new has not been called yet“
    – I try to see the struc­ture of fr.mort object to find myself solu­tion but i can to to see.
    –I do not under­stand what the term “series =‘male’” in lines(x,series=‘male’,lwd=2,col=1) in your code means, could you explain?
    I am new in sta­tis­tics and R, i am sorry if i bring you any incon­ve­nient, but your graph is very impres­sive, PCA in FDA of your paper too.

    • http://robjhyndman.com Rob J Hyndman

      I’m sorry. A cou­ple of cru­cial lines were omit­ted. Try now.

      fr.mort is a demog­data object. To see what is in it, use str(fr.mort)

      series=“male” means to select the male mor­tal­ity rates.

  • http://www.datamilk.com Ross

    Hi Rob

    Is there a way of mak­ing ani­ma­tions from graphs cre­ated with qplot() rather than plot ?

  • http://yihui.name Yihui

    Thanks, Rob. The lat­est ver­sion of the animation pack­age can deal with Sweave eas­ily now. You may want to look at the saveLatex() func­tion as well as the demo('Sweave_animation') and demo('rgl_animation').

  • Fer­nando

    Hi, i was won­der­ing how many years are nec­es­sary for a good func­tional analysis?

    • http://robjhyndman.com Rob J Hyndman

      It depends on what you are try­ing to do, just as with any area of sta­tis­ti­cal analy­sis. The small­est num­ber of obser­va­tions I’ve used for fore­cast­ing is about 30.

  • Ric

    Hi, I was try­ing to fol­low the instruc­tions to do an ani­ma­tion in R but couldn’t read the impor­tant line after “Then the fol­low­ing com­mand will do the magic:”.….., so I was not able to fin­ish. Thanks

    • http://robjhyndman.com Rob J Hyndman

      I’ve now split the line in two.

      • Ric

        Thanks, now I can see it.   This com­mand is to be used in a Latex pre­sen­ta­tion, is it pos­si­ble to do the pre­sen­ta­tion in Power Point? What would be the way to do it?

        • Rob J Hyndman

          No idea. I never use PowerPoint.

  • Pingback: Presenting Mortality data with R and LateX | R bloggerqvist