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

2

10

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.

Howard answered 23/1, 2017 at 18:30 Comment(2)
You can generate your three plots with less code as follows: Plotlist <- lapply(split(iris, iris$Species), function(S){ ggplot(S, aes(x = Sepal.Width, y = Sepal.Length)) + geom_point() })Writing
Ah... Nice and succinct. Thanks for the tip!Howard
S
9

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))
Swordtail answered 23/1, 2017 at 19:23 Comment(1)
also worked for me and saved my hairy ass on Friday evening!Cableway
B
4

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")
Bouncing answered 7/4, 2018 at 13:28 Comment(1)
Me too, baptiste's workaround changed nothing. Yours did +1.Disney

© 2022 - 2025 — McMap. All rights reserved.