Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Using marrangeGrob to make pdf results in blank first page

I'm making some pdf files with multiple graphs on each page, and, when I use marrangeGrob from the gridextra package to make those graphs, the first page is always blank. How can I make the plots start on the first page? Here's some example code:

library(gridextra)
library(ggplot2)
data(iris)

Plotlist <- list()

Plotlist[[1]] <- ggplot(data = subset(iris, Species == "setosa"),
                         aes(x = Sepal.Width, y = Sepal.Length)) +
      geom_point()

Plotlist[[2]] <- ggplot(data = subset(iris, Species == "versicolor"),
                        aes(x = Sepal.Width, y = Sepal.Length)) +
      geom_point()

Plotlist[[3]] <- ggplot(data = subset(iris, Species == "virginica"),
                        aes(x = Sepal.Width, y = Sepal.Length)) +
      geom_point()

pdf("iris.pdf", width = 8.5, height = 11)
marrangeGrob(Plotlist, nrow = 2, ncol = 1)
dev.off()

The 2nd page of the pdf even says at the top, "Page 1 of 2", so there's some disconnect somewhere.

like image 990
shirewoman2 Avatar asked Jan 23 '17 18:01

shirewoman2


2 Answers

My guess is that something's recently changed in ggplot2 to call a grid function to evaluate a grid unit that requires an open device.

You can try this workaround,

glist <- lapply(Plotlist, ggplotGrob)
ggsave("iris.pdf", marrangeGrob(glist, nrow = 2, ncol = 1))
like image 160
baptiste Avatar answered Oct 14 '22 07:10

baptiste


A blank first page still appeared for me when using @baptiste's workaround. The functions from ggpubr for multi-page plotting from a list of plots worked for me instead (from here):

multi.page <- ggpubr::ggarrange(plotlist = glist, nrow = 1, ncol = 2) 
ggpubr::ggexport(multi.page, filename = "multi.page.ggplot2.pdf")
like image 30
meenaparam Avatar answered Oct 14 '22 08:10

meenaparam