Multiple graphs in a for loop with Sweave

My piece 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 graph (from the first iteration). I would like all 10 graphs to be printed. What am I doing wrong? I tried replacing dev.new() with frame() and plot.new() , but nothing happened.

+6
source share
1 answer

Since @rawr offers the easiest solution - switch to knitr (there really is no reason not to do this at all!) And put fig.keep="all" in your code options (if you switch to knitr you don't need fig=TRUE anymore ... including numbers works automatically, fig.keep="none" is analogous to fig=FALSE )

Alternatively, if you want to stick with Vanilla Sweave, check out the Sweave Guide . 17:

A.9 Creating multiple shapes from the same piece of shape does not work

Note that you want to create multiple graphs in a loop like

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

This currently does not work, because Sweave allows you to use only one graph for each fragment. The simple reason is that Sweave opens the postcript device before executing the code and closes it afterwards. If you need to build a graph in a loop, you need to program it along the lines

 <<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="") } @ 
+9
source

Source: https://habr.com/ru/post/970593/


All Articles