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?
To arrange multiple ggplot2 graphs on the same page, the standard R functions - par() and layout() - cannot be used. The basic solution is to use the gridExtra R package, which comes with the following functions: grid. arrange() and arrangeGrob() to arrange multiple ggplots on one page.
Combine multiple ggplot on one page.Use the function ggarrange() [ggpubr package], a wrapper around the function plot_grid() [cowplot package]. Compared to plot_grid(), ggarange() can arrange multiple ggplots over multiple pages.
To draw multiple curves in one plot, different functions are created separately and the curve() function is called repeatedly for each curve function. The call for every other curve() function except for the first one should have added an attribute set to TRUE so that multiple curves can be added to the same plot.
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 . . .
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With