rggplot2pdfgridextraggsave

How to create page margins in a ggsave() pdf file


I am trying to print a series of ggplot graphs in a multipage PDF. Everything works fine except I can't figure out how to define the page margins. I want to produce 8.5x11 pages with 1" margins on all sides. The following code produces a PDF page that is only 6.5x9. When printed on a normal sheet of paper, the margins are fine because the PDF is centered, but when viewed in a PDF viewer like Acrobat, there are no margins.

library(ggplot2)
library(gridExtra)

x <- c(5,7,2,4,9)
y <- c(2,10,15,8,14)
df <- data.frame(x,y)
myfunct <- function(i){
  p<-ggplot(df, aes(x=x,y=y*i)) +
    geom_point()
  return(p)
}
myGrobs <- lapply(1:10, myfunct)
page <- marrangeGrob(myGrobs, nrow=3, ncol=1)
ggsave("test pdf.pdf", plot = page, device = "pdf", 
        width = 6.5, height = 9, units="in")

Solution

  • We can use grid::viewport() to define the region of the page that we want to draw the plots.

    First, create the grobs.

    library(ggplot2)
    library(grid)
    library(gridExtra)
    
    x <- c(5,7,2,4,9)
    y <- c(2,10,15,8,14)
    df <- data.frame(x,y)
    
    myfunct <- function(i){
      ggplot(df, aes(x=x, y=y*i)) + geom_point()
    }
    myGrobs <- lapply(1:10, myfunct)
    page <- marrangeGrob(myGrobs, nrow=3, ncol=1, top = "")
    

    Then we can draw the plots in the predefined viewport:

    vp <- viewport(x = 0.5, y = 0.5, 
                   width = unit(6.5, "inches"),
                   height = unit(9, "inches"))
    cairo_pdf("controlled_margins_1.pdf", width = 8.5, height = 11)
    for(i in seq_along(page)) {
      grid.newpage()
      pushViewport(vp)
      grid.draw(page[[i]])
      popViewport()
    }
    dev.off()
    

    or as OP mentioned in the comments:

    pdf("controlled_margins_2.pdf", width = 6.5, height = 9, paper="letter") 
    for(i in seq_along(page)) { 
      grid.newpage() 
      pushViewport(viewport()) 
      grid.draw(page[[i]]) 
      popViewport() }
    dev.off()
    

    As you can see we have the right page size and right margins (the 10th plot obviously has empty space at the bottom):