[R] Sweave with layout() and loop

Friedrich.Leisch@tuwien.ac.at Friedrich.Leisch at tuwien.ac.at
Mon Jun 27 12:52:11 CEST 2005


>>>>> On Sun, 26 Jun 2005 11:36:14 -0700 (PDT),
>>>>> Mikkel Grum (MG) wrote:

  > When I try the following code with the Windows
  > graphics window, a new window is opened for each
  > multiple of four images I produce.

  > par(layout(matrix(c(1,2,3,4), 2, 2, byrow = TRUE)),
  > mar = c(2, 3, 2, 3))

  > for (i in 1:n) {
  >  image(... )
  >  }

  > When I try to do the same with Sweave to produce a pdf
  > document, I only get one graphic with the first four
  > graphs.  How do I get the rest when n is greater than
  > four?

  > <<Plots, fig=TRUE, eps=FALSE, echo=FALSE,   
  > results=hide, width=6.8, height=9.8>>=

  > par(layout(matrix(c(1,2,3,4), 2, 2, byrow = TRUE)),
  > mar = c(2, 3, 2, 3))

  > for (i in 1:n) {
  >  image(... )
  >  }

  > Any ideas?

FAQ A.8:

A.8  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="")  
}  
@

-- 
-------------------------------------------------------------------
                        Friedrich Leisch 
Institut für Statistik                     Tel: (+43 1) 58801 10715
Technische Universität Wien                Fax: (+43 1) 58801 10798
Wiedner Hauptstraße 8-10/1071
A-1040 Wien, Austria             http://www.ci.tuwien.ac.at/~leisch




More information about the R-help mailing list