baptiste / gridExtra

Miscellaneous Functions for "Grid" Graphics
http://cran.r-project.org/web/packages/gridExtra/index.html
15 stars 4 forks source link

Consecutive arrangeGrob Plots Are Overlaid #27

Closed DarioS closed 8 years ago

DarioS commented 8 years ago

Shouldn't the PDF document have two pages, not one page with two overlaid plots ?

library(grid)
library(gridExtra)
library(ggplot2)
boxPlot <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_boxplot()
violinPlot <- ggplot(mtcars, aes(factor(cyl), mpg)) + geom_violin()

pdf("mileage.pdf")
bothPlots <- arrangeGrob(boxPlot, violinPlot, nrow = 2, top = textGrob("First Title"))
grid.draw(bothPlots)
bothPlots <- arrangeGrob(violinPlot, boxPlot, nrow = 2, top = textGrob("Second Title"))
grid.draw(bothPlots)
dev.off()

If I use grid.draw on the boxplot and violin plot separately, I get a 2 page PDF, as desired.

pdf("testSeparately.pdf")
grid.draw(boxPlot)
grid.draw(violinPlot)
dev.off()

It seems that arrangeGrob is the cause of the problem.

baptiste commented 8 years ago

works as intended, in standard grid you're supposed to explicitly call grid.newpage() if you want grid.draw() to draw on a blank page, i.e. the default behaviour is to add things to the page, not assume that we want to erase what was there before and replace it. ggplot2, in contrast, has always gone in the other direction. Its recently-added grid.draw method is just a wrapper around print.ggplot, which defaults to newpage=TRUE.

Note that grid.arrange (somewhat inconsistently) also defaults to newpage=TRUE, so you could use that instead.