I am trying to compile four graphs with grid.arrange() and to reduce the margins of each plot so that they are nice and compact. I would like to use theme(plot.margin=unit(c(x, x, x , x), "cm")) (other solutions welcome).
A similar question was asked a while ago: here
However, plot.margin now requires the argument units which does not have a default. I could not find any explanations about what R expects in this argument. Would someone have an example?
For a reproducible example, please use the one provided in the old question. Thanks!
We have unit(c(t, r, b, l), "cm") with margin sizes at the top, right, bottom, and left, respectively. And actually there is a default value:
theme_get()$plot.margin
# [1] 5.5pt 5.5pt 5.5pt 5.5pt
An example:
qplot(mpg, wt, data = mtcars) +
theme(plot.margin = unit(c(5, 15, 25, 35), "pt"),
plot.background = element_rect(fill = "grey90"))

You can use "cm", "lines" or "points" for the units argument. Below is some example code. Just change the last argument inside theme(plot.margin=unit(c(x, x, x , 1.5), "lines") to align the 3 graphs at the beginning.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With