Search code examples
rsweave

Multiple plots in a for loop with Sweave


My chunk in Sweave:

<<fig=TRUE,echo=FALSE>>=
for(i in 1:10) {
  plot(rep(i,10))
  dev.new()
}
@

In the resulting pdf I get only one plot (from the first iteration). I would like to have all of the 10 plots printed. What am I doing wrong? I tried replacing dev.new() with frame() and plot.new() but nothing happened.


Solution

  • As @rawr suggests the easiest solution is to switch to knitr (there's really no reason at all not to!) and put fig.keep="all" in your code chunk options (if you switch to knitr you don't need fig=TRUE any more ... including figures works automatically, fig.keep="none" is the analogue of fig=FALSE)

    Alternatively, if you want to stick with vanilla Sweave, check the Sweave manual p. 17:

    A.9 Creating several figures from one figure chunk does not work

    Consider that you want to create several graphs in a loop similar to

    <<fig=TRUE>>
    for (i in 1:4) plot(rnorm(100)+i)
    @
    

    This will currently not work, because Sweave allows only one graph per figure chunk. The simple reason is that Sweave opens a postscript device before executing the code and closes it afterwards. If you need to plot in a loop, you have to program it along the lines of

    <<results=tex,echo=FALSE>>=
    for(i in 1:4){
    file=paste("myfile", i, ".eps", sep="")
    postscript(file=file, paper="special", width=6, height=6)
    plot(rnorm(100)+i)
    dev.off()
    cat("\\includegraphics{", file, "}\n\n", sep="")
    }
    @