Mehdi.K
Mehdi.K

Reputation: 371

Reduce all plot margins in ggplot2 and grid.arrange

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!

Upvotes: 3

Views: 7425

Answers (2)

Tbremm
Tbremm

Reputation: 36

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)

Upvotes: 2

Julius Vainora
Julius Vainora

Reputation: 48191

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

Upvotes: 5

Related Questions