首页 > 解决方案 > 使用 grid.arrange 创建的 ggplot 中标题上方的边距

问题描述

我有两个可以像这样创建的 ggplots:

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")))

现在输出如下所示:

在此处输入图像描述

在这里看不到它,因为它是白底白字,但我想在标题上方的输出图像中创建更多空间。而且我不确定该怎么做。这里描述了如何在 grid.arrange 中的单个图之间添加空间 Margins,但我没有设法仅在标题上方添加空间。

标签: rggplot2gridextrar-grid

解决方案


利用arrangeGrob您可以通过zeroGrob如下方式在标题顶部添加一些边距:

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)


推荐阅读