Plotting over multiple pages
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?
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 . . .
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".