2

How can I keep saving figures to a pdf with R. Consider the following example:

require(ggplot2)
require(gridExtra)
TopFolder <- "...directory on my drive"
setwd(TopFolder)


pdf(file = paste(TopFolder,"figures","example.pdf",sep = "\\"))

g <- list()
for(i in 1:4){
  dat <- data.frame(d1 = c(1:10),
                    d2 = runif(10))
  g[[i]] <- qplot(x = d1, y = d2,
        data = dat)
}
grid.arrange(g[[1]],g[[2]],g[[3]],g[[4]])  

for(i in 1:6){
  dat <- data.frame(d1 = c(1:20),
                    d2 = runif(20))
  qplot(x = d1, y = d2,
                  data = dat)
} 

dev.off()

My question is: Why doesn't the sesond set of plots i.e. the 6 generated by the second for loop show up in the pdf file? The only obvious difference I can spot is that I store the plots in the first loop and do't in the second. Why doesn't R generate these plots in the second loop and save them in the pdf after completion?

The result I would expect from this example would be to have the first page of the pdf with the four subplots and then have 6 pages following with one figure in each page. Why isn't this being generated? I would have thought that R would keep generating the figures in the file until dev.off() was called?

KatyB
  • 3,920
  • 7
  • 42
  • 72
  • 6
    Without testing: You probably need to wrap `qplot` in `print`. – Roland Aug 12 '13 at 09:54
  • 1
    BTW have a look at `?file.path`. It is cleaner and more platform independent than `paste`: `file.path(TopFolder,"figures","example.pdf")`. – sgibb Aug 12 '13 at 09:57
  • 1
    In `pdf` you sohuld look at `onefile = TRUE` – Simon O'Hanlon Aug 12 '13 at 09:59
  • onefile is set to true (default). @Roland This works, although I don't understand why it needs to be wrapped in paste during this command and not with the other ggplot? – KatyB Aug 12 '13 at 10:05
  • 1
    Because you print it with `grid.arrange`. Inside functions (which includes `for`), all ggplot2 graphs need to be printed explicitly. You can use either `print` or `grid.draw` (which is called by `grid.arrange`). – Roland Aug 12 '13 at 10:08
  • see also here: http://stackoverflow.com/questions/1395410/how-to-print-r-graphics-to-multiple-pages-of-a-pdf-and-multiple-pdfs – holzben Aug 12 '13 at 10:10

1 Answers1

4

... and all putting all commands from above together

require(ggplot2)
require(gridExtra)
TopFolder <-"...directory on my drive"
setwd(TopFolder)


pdf(file = file.path(TopFolder,"figures","example.pdf"), onefile=TRUE)
g <- list()
for(i in 1:4){
dat <- data.frame(d1 = c(1:10),
                  d2 = runif(10))
g[[i]] <- qplot(x = d1, y = d2,
                  data = dat)
}
grid.arrange(g[[1]],g[[2]],g[[3]],g[[4]])  

gg <- list()

# each of this plots will be on a separate page
for(i in 1:6){
  dat <- data.frame(d1 = c(1:20),
                    d2 = runif(20))

  # here a print is necessary
  print(qplot(x = d1, y = d2,
        data = dat))
} 
dev.off()
holzben
  • 1,459
  • 16
  • 24