Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotting over multiple pages

Tags:

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?

like image 743
Mike Dewar Avatar asked Aug 03 '10 16:08

Mike Dewar


People also ask

How do I arrange multiple Ggplots?

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.

How do I put two Ggplots on top of each other?

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.

How do you plot multiple curves on the same graph?

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.


1 Answers

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 . . .

like image 133
Elaine Avatar answered Sep 23 '22 08:09

Elaine