2
votes

Suppose I have a function

plotSingle <- function(x) {
   plot(x)
}

I want to use this in a loop in Sweave to generate 20 pages with 1 plot on each page. For example:

\begin{figure}[htb]
\caption{}
\centering
<<fig=TRUE,echo=FALSE>>=
for(loop in 1:20) {
    plotSingle(loop)
    cat('\\newpage')
}
@
\end{figure}

However, this will only generate 1 plot on 1 page, not the 20 on 20 pages that I'm after.

How do I adjust the above Sweave code in order to do what I want?

1

1 Answers

0
votes

You should add plot.new or its alias frame() and no need to to cat('\\newpage')

<<,fig=TRUE,echo=FALSE>>=
plotSingle <- function(x) {
   plot.new()   ##  ~ frame()
   plot(0)
}
for(i in 1:3) plotSingle(mtcars)
@

EDIT with layout:

I think that knitr do some optimizations when he found the same plot statement. That

<<,echo=FALSE>>=

plotSingle <- function(x) {

   layout(matrix(1:3,nrow=3))
   plot(0,main=x)          ## the 3 plots statement here are different
   plot(1,main=x)          ## you can just change the title also and it will works
   plot(2,main=x)          ## keep in mind to give knitr different plot statement.

}

 for(i in 1:5)  plotSingle(i)  ## you have also to give different iodex here
                               ## plotSingle(0) will not work for example.
@