【问题标题】:Margin above title in ggplot created with grid.arrange使用 grid.arrange 创建的 ggplot 中标题上方的边距
【发布时间】:2021-04-07 12:53:22
【问题描述】:

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

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

现在输出如下所示:

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

【问题讨论】:

  • 如何使用padding=unit(1, "cm") 在注释周围增加一点空间

标签: r ggplot2 gridextra r-grid


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    你能接受另一个包裹吗?

    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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-08
      • 2020-05-07
      • 2015-11-26
      • 2016-02-29
      相关资源
      最近更新 更多