49

How can I increase the area around a plot area in ggplot 2 to give my axis titles some breathing room. I am aware of vjust and hjust (as below), however, I can't seem to create actual space around the plotting area to move my axes titles onto.

p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p

p<- p + theme(axis.title.x = element_text(family="Times",size=20,face="bold",colour = "Black",vjust=-1,hjust=0.5)) 
p

enter image description here

Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
Elizabeth
  • 6,391
  • 17
  • 62
  • 90

1 Answers1

92

Margins around plot can be modified with theme(), plot.margin = and function margin() where you provide size of margins starting with top, then right, bottom and left, and units (default is "pt").

ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point() + 
  theme(axis.title.x = element_text(family = "Times",size = 20,
                face = "bold",colour = "Black",vjust = -1,hjust = 0.5))+
  theme(plot.margin = margin(1,1,1.5,1.2, "cm"))
Didzis Elferts
  • 95,661
  • 14
  • 264
  • 201
  • 13
    The default for `theme_bw()` is now `unit(c(5.5, 5.5, 5.5, 5.5), "points")`. – CCurtis Mar 29 '16 at 22:08
  • 3
    I think grid is no longer needed, I'm using ggplot 2.2.0 – snaut Nov 29 '16 at 10:37
  • 22
    In the case it's helpful to anyone else, here are the arguments to margin (denoting to which side each value corresponds): `margin(t = 0, r = 0, b = 0, l = 0, unit = "pt")` – Joshua Rosenberg Mar 20 '18 at 00:14
  • 1
    Defaults are now: ``margin(half_line, half_line, half_line, half_line)``, where ``half_line <- base_size / 2`` ;-) – PatrickT Dec 16 '18 at 14:00
  • How to add a title? – Frank Oct 05 '21 at 21:28
  • I am confused by these comments. The answer does not mention a `margin()` function, so what are the comments that mention `margin()` talking about? Are these intended to imply that using `unit()` is now deprecated? – randy Jan 15 '22 at 00:30
  • @randy Both solutions work but the `margin()` version is newer. I updated the answer. – Didzis Elferts Jan 15 '22 at 09:57