0

I'm trying to plot a large number of graphs by looping over some data, but graphs produced when the plotting functions are encapsulated within a for loop are corrupted PDFs.

I've reduced it down to a minimal example here; this should produce 1.pdf as expected, but 2.pdf and 3.pdf generated inside the loop are slightly smaller files, and don't open in PDF reader software.

i <- 1

pdf(paste(i,'.pdf',sep=''))
ggplot(NULL,aes(x=i, y=i)) +
  geom_point() +
  coord_cartesian(xlim = c(0, 10), ylim = c(0, 10)) +
  ggtitle(paste('i =', i))
dev.off()


for(i in 2:3) {
  pdf(paste(i,'.pdf',sep=''))
  ggplot(NULL,aes(x=i, y=i)) +
    geom_point() +
    coord_cartesian(xlim = c(0, 10), ylim = c(0, 10)) +
    ggtitle(paste('i =', i))
  dev.off()
}

What's wrong?

animuson
  • 53,861
  • 28
  • 137
  • 147
Andrew Steele
  • 493
  • 6
  • 16

1 Answers1

2

You have to print it: print(ggplot(...))

shadow
  • 21,823
  • 4
  • 63
  • 77