减小ggplot2和grid.arrange中所有图形边距的大小

3
我正在尝试使用grid.arrange()编译四个图形,并减小每个图的边距,使它们更加紧凑。我想使用theme(plot.margin=unit(c(x, x, x , x), "cm"))(欢迎其他解决方案)。
以前有类似的问题:这里 然而,plot.margin现在需要参数units,该参数没有默认值。我找不到任何关于R对此参数的期望的解释。是否有人有例子?
请使用旧问题中提供的可重复性示例。
谢谢!
2个回答

5
我们有一个带有上、右、下、左边距大小的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"))

enter image description here


8
针对楼主:一个有用的记忆口诀是 trouble,以便记住顺序。 - Dan
我意识到我的括号写错了,R 给出了以下错误信息:Error in unit(c(0.1, 0.1, 0.1, 0.1)) : argument "units" is missing, with no default 因此,我认为 unitunits 是两个不同的参数... 我犯了个错误。 - Mehdi.K
@Mehdi.K,我明白了。无论如何,你的问题都是有意义的,因为我相信theme_get()$plot.margin并不是很显眼,但也可能很有用。 - Julius Vainora

2
您可以使用“cm”,“lines”或“points”作为单位参数。以下是一些示例代码。只需更改主题(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)

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