26

I'm trying to write a function that plots a ggplot facet_wrap plot over multiple pages. It's just a hack, as this feature seems to be on the ggplot2 feature to-do list. I do some small calculations to find the number of pages I'm going to need, the number of rows of my data.frame that I need per page etc. I'm pretty confident this all works.

pdf(filename)
for (i in seq(num_pages)){
    slice = seq(((i-1)*num_rows)+1,(i*num_rows))
    slice = slice[!(slice > nrow(df.merged))]
    df.segment=df.merged[slice,]
    p <- ggplot(df.segment, aes(y=mean,x=phenotype))
    p <- p + geom_bar(stat="identity",fill="white",colour="black") 
    p + facet_wrap("ID",scales="free_y",ncol=n_facets,nrow=n_facets)
}
dev.off()

My problem is that, by wrapping it all up in a for loop like this, in between the pdf() and dev.off() functions, is that the for loop doesn't seem to wait for ggplot to do its thing, and blazes through its loop very quickly and outputs an invalid PDF.

If I set i = 1, start the pdf(), run the above code inside the for loop, then set i=2, then run the code, and so on until I get bored (i=3) then turn off the device the resulting PDF is brilliant.

Is there a way I can get the for loop to wait for the final line to finish plotting before moving onto the next iteration?

Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
Mike Dewar
  • 10,945
  • 14
  • 49
  • 65

2 Answers2

31

I think the problem is that you need print() around your last line (p+ ...) to get it to actually print to the device inside the for loop . . .

Elaine
  • 396
  • 3
  • 2
  • wow that completely works. I had no idea that print could be used like this. – Mike Dewar Aug 03 '10 at 18:02
  • It's because `p` is an object. The last line of your code modifies the `p` object, but then you want to `print()` it to the device. – JoFrhwld Aug 03 '10 at 19:29
  • Yup, it's a common obstacle. Sometimes I write a function in ggplot2, and omit `print()` around the final part, hence get no output... – aL3xa Aug 03 '10 at 19:46
  • I think we all make that mistake. I posted a near identical question a few months ago: http://stackoverflow.com/questions/2277166/saving-dotplot-to-pdf-in-r – Jared Aug 03 '10 at 20:55
  • Heh... me, too. One of the pitfalls of the interactive console. – Matt Parker Aug 04 '10 at 13:07
  • is print overloaded for objects of class `class(p)`? I feel that I'm close to understanding something here... – Mike Dewar Aug 04 '10 at 21:58
6

Exactly. Page 39 of the ggplot2 book tells us that when you create ggplot2 objects, you can "Render it on screen, with print(). This happens automatically when running interactively, but inside a loop or function, you'll need to print() it yourself".