3

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.

tjebo
  • 21,977
  • 7
  • 58
  • 94
Robin Kohrs
  • 655
  • 7
  • 17

2 Answers2

3

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)

stefan
  • 90,330
  • 6
  • 25
  • 51
3

Can you live with another package?

library(patchwork)

plot_spacer()/ (gg1 + ggtitle("there is now space above")) / gg2 + plot_layout(heights = c(.5,1,1)) 

Or set the title margin in the first plot

gg1 = ggplot(df1) + geom_point(aes(x=x, y=y1)) +
  ggtitle("there is now space above") +
  theme(plot.title = element_text(margin = margin(t = 1, unit = "in")))

gg1 / gg2 

tjebo
  • 21,977
  • 7
  • 58
  • 94