3

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!

Mehdi.K
  • 371
  • 4
  • 15

2 Answers2

5

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

enter image description here

Julius Vainora
  • 47,421
  • 9
  • 90
  • 102
  • 8
    To the OP: A helpful mnemonic to remember the order is ***tr**ou**bl**e*. – Dan Jan 11 '19 at 11:54
  • I realized that I had made a mistake with my parentheses, and R was showing me the following error message: ```Error in unit(c(0.1, 0.1, 0.1, 0.1)) : argument "units" is missing, with no default``` Therefore, I thought ```unit```and ```units``` were two different arguments... my bad. – Mehdi.K Jan 11 '19 at 12:25
  • @Mehdi.K, I see. It happens that your question made sense anyway as this `theme_get()$plot.margin` is, I believe, not very visible, and also may be useful. – Julius Vainora Jan 11 '19 at 12:27
2

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)
Tbremm
  • 36
  • 5