26

Possible Duplicate:
Generate multiple graphics from within an R function

Very strange thing happening to me: the following code fails to print to pdf device:

outnames <- c("1.pdf", "2.pdf")
for (n in outnames){
    pdf(n)
    qplot(1:10)
    dev.off()
}

won't print anything to pdf, even though a pdf file is generated. However,

pdf(outnames[2])
qplot(1:10)
dev.off()

will work perfectly well. Any idea why? Reproduced in R 2.11.1.

Community
  • 1
  • 1
gappy
  • 10,095
  • 14
  • 54
  • 73

2 Answers2

41

Gappy, that smells like the FAQ 7.22 -- so please try print(qplot(1:10)).

Dirk Eddelbuettel
  • 360,940
  • 56
  • 644
  • 725
13

@Dirk explains why this is happening (auto printing turned off), but an alternative to opening the device, generating the plot on the device, closing the device is ggsave(). For example:

p1 <- qplot(1:10)
ggsave("p1.pdf", plot = p1)

or via a loop:

outnames <- c("1.pdf", "2.pdf")
for (n in outnames){
    p2 <- qplot(1:10)
    ggsave(n, plot = p2)
}

At the end of that we have all the generated plots we asked for.

> list.files(pattern = ".pdf$")
[1] "1.pdf"                  "2.pdf"                 
[3] "p1.pdf"
Ken Williams
  • 22,756
  • 10
  • 85
  • 147
Gavin Simpson
  • 170,508
  • 25
  • 396
  • 453