170

I have several faceted histograms (obtained with the command below) which are nicely plotted one under the other. I would like to increase the spacing between them, however, they are tight.

I looked at the doc but didn't find a parameter for this.

qplot (Happiness.Level, Number.of.Answers, data=mydata, geom="histogram") + facet_grid (Location ~ .) 
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
wishihadabettername
  • 14,231
  • 21
  • 68
  • 85
  • A side comment that I found another way to approach this (used a faced_wrap instead of facet_grid and the resulting chart is better looking). I'm still interested if there is a way to address the original question. – wishihadabettername Sep 10 '10 at 03:04
  • 3
    Try theme_get() for a slew of hidden options that you can adjust with opts() – Brandon Bertelsen Sep 27 '10 at 22:48

2 Answers2

253

Use the theme function:

library(grid)

p + theme(panel.spacing = unit(2, "lines"))

See also here: Slicing plots generated by ggplot2

Community
  • 1
  • 1
rcs
  • 67,191
  • 22
  • 172
  • 153
  • http://stackoverflow.com/questions/12252750/alter-just-horizontal-spacing-between-facets-ggplot2 – user4786271 Aug 12 '15 at 08:47
  • 10
    Due to another update, the incantation is now `theme(panel.margin = unit(2, "lines"))` – David J. Harris Nov 08 '16 at 16:49
  • 22
    Update - is now `theme(panel.spacing = unit(1, "lines"))` – Mr.ecos Feb 12 '17 at 21:01
  • 1
    This works without the ``grid`` package. In my experience the x labels of two side-by-side plots often overlap (the greatest label on the lhs and the smallest label on the rhs). One solution to fix the output is to ``ggsave`` with a greater width than the default. But I find ``theme(panel.spacing = unit(1, "lines"))`` nicer because it also works for the pop-up plot window. – PatrickT Oct 16 '17 at 15:50
  • 1
    I was getting an error "Error: widths must be a unit object" but changing from "lines" to "pt" worked as in `theme(panel.spacing = unit(15, "pt")`. – Omar Wasow Feb 08 '22 at 16:45
37

Just to add to @rcs response:

# Change spacing between facets on both axis
p + theme(panel.spacing = unit(2, "lines"))

# Change horizontal spacing between facets
p + theme(panel.spacing.x = unit(2, "lines"))

# Change vertical spacing between facets
p + theme(panel.spacing.y = unit(2, "lines"))
Gorka
  • 3,555
  • 1
  • 31
  • 37