Search code examples
rmarginsr-grid

Add margins with grid R package


I don't know how to specify margins for PDF printing with grid R package.

I create a grid.arrange() object and I put it in a PDF like this :

pdf('test.pdf',11.69,8.27)
grid.arrange(textGrob('text1', gp=gpar(cex=4)),
             ncol=1, main=textGrob('title', gp=gpar(cex=1.5)),
             widths = c(1), heights = c(1))
dev.off()

But the title is push at the top edge of the sheet. I would like to add margins. If I add a textGrob instead of the main= function for the title, I can keep it away from the top but it's not a solution for me because I have to put graphs and they are close to the edge too.


Solution

  • arrangeGrob has a viewport argument,

    vp = viewport(height=unit(0.8, "npc"), 
                              width=unit(5, "cm"))
    
    g = arrangeGrob(textGrob('text1', gp=gpar(cex=4)),
                  top = textGrob('title', gp=gpar(cex=1.5)),  
                  vp=vp)
    grid.newpage()
    grid.rect(vp=vp)
    grid.draw(g)
    

    enter image description here