ggplot和grid.arrange创建的图形中,标题上方的边距是什么?

3

我可以像这样创建两个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")))

现在输出结果看起来像这样:

enter image description here

虽然在这里看不到它,因为是白色在白色上,但我想在输出图像上方创建更多的空间。我不太确定如何做。这里描述了如何在单个绘图之间添加空间 (grid.arrange中的绘图之间的边距) ,但我无法仅在标题上方添加空间。

1
使用 padding=unit(1, "cm") 如何?这会在注释周围添加一些空间。 - user20650
2个回答

3
利用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)


3

您能接受使用另一个软件包吗?

library(patchwork)

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

或者在第一个图中设置标题边距

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 


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接