减少 ggplot2 和 grid.arrange 中的所有图边距

Reduce all plot margins in ggplot2 and grid.arrange

我正在尝试用 grid.arrange() 编译四张图,并减少每张图的边距,使它们美观紧凑。我想使用 theme(plot.margin=unit(c(x, x, x , x), "cm"))(欢迎使用其他解决方案)。

前段时间有人问过类似的问题: here

但是,plot.margin 现在需要没有默认值的参数 units。我找不到关于 R 在这个论点中期望什么的任何解释。有人能举个例子吗?

对于可重现的示例,请使用旧问题中提供的示例。 谢谢!

我们 unit(c(t, r, b, l), "cm") 分别在顶部、右侧、底部和左侧设置了边距大小。实际上有一个默认值:

theme_get()$plot.margin
# [1] 5.5pt 5.5pt 5.5pt 5.5pt

一个例子:

qplot(mpg, wt, data = mtcars) + 
  theme(plot.margin = unit(c(5, 15, 25, 35), "pt"),
        plot.background = element_rect(fill = "grey90"))

您可以使用 "cm"、"lines" 或 "points" 作为单位参数。下面是一些示例代码。只需更改 theme(plot.margin=unit(c(x, x, x , 1.5), "lines") 中的最后一个参数,使开头的 3 个图对齐。

library(ggplot2)
library(grid)
library(gridExtra)

test1 <- qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.text=element_text(size=16),
axis.title=element_text(size=18),axis.title.x=element_text(size=14),
plot.margin = unit(c(1, 1, 0, 1.4), "lines"),
legend.text=element_text(size=16))

test2 <- qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.text=element_text(size=16),
axis.title=element_text(size=18),axis.title.x=element_text(size=14),
plot.margin = unit(c(1, 1, 0, 1.2), "lines"),
legend.text=element_text(size=16))

test3 <- qplot(rnorm(100)) +
ggtitle("Title") +
theme(axis.text=element_text(size=16),
axis.title=element_text(size=18),axis.title.x=element_text(size=14),
plot.margin = unit(c(1, 1, 0, 1), "lines"),
legend.text=element_text(size=16)) 



grid.arrange(test1,test2,test3, nrow=3)