Search code examples
rggplot2gridextrar-grid

Margin above title in ggplot created with grid.arrange


I have two ggplots that I can created like this:

df1 = data.frame(x=1:10, y1=11:20, y2=21:30)
gg1 = ggplot(df1) + geom_point(aes(x=x, y=y1))
gg2 = ggplot(df1) + geom_point(aes(x=x, y=y2))
grid.arrange(gg1, gg2, top=textGrob("Here should be some space above",
                                    gp=gpar(fontsize=18,
                                            fontfamily="Times New Roman")))

Now the output looks like this:

enter image description here

One does not see it here as it is white on white, but I would like to create more space in the output-image above the title. And I'm not really sure on how to do it. Here is described on how to add space between the single plots Margins between plots in grid.arrange , but I did not manage to just add space above the header.


Solution

  • Making use of arrangeGrob you could add some margin on top of your header via a zeroGrob like so:

    library(ggplot2)
    library(gridExtra)
    library(grid)
    
    df1 = data.frame(x=1:10, y1=11:20, y2=21:30)
    gg1 = ggplot(df1) + geom_point(aes(x=x, y=y1))
    gg2 = ggplot(df1) + geom_point(aes(x=x, y=y2))
    
    title <- textGrob("Here should be some space above",
                      gp=gpar(fontsize=18, fontfamily="Times New Roman"))
    
    # Add a zeroGrob of height 2cm on top of the title
    title <- arrangeGrob(zeroGrob(), title, 
                        widths = unit(1, 'npc'), 
                        heights = unit(c(2, 1), c('cm', 'npc')),
                        as.table = FALSE)
    grid.arrange(gg1, gg2, top = title)