Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reduce all plot margins in ggplot2 and grid.arrange

Tags:

r

ggplot2

margins

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!

like image 714
Mehdi.K Avatar asked Nov 18 '25 07:11

Mehdi.K


2 Answers

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

like image 166
Julius Vainora Avatar answered Nov 20 '25 21:11

Julius Vainora


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)
like image 23
Tbremm Avatar answered Nov 20 '25 23:11

Tbremm



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!