Search code examples
rggplot2distanceboxplotfacet-grid

How to adjust the distance between the facet_grid frame and boxplots using ggplot_build & ggplot_gtable


We are presenting outcome data using boxplots and group these for different approaches using facet_grid with ggplot2 and geom_boxplot.

We would like to add more space between the boxplots and the frame of the facet_grid as shown in the graphic below.

The code we used included ggplot_build and gglot_table. Which parameter of ggplot_build needs to be set to get more space in the panels?

enter image description here

require(ggplot2)
require(grid)
dat <- rbind(data.frame(approach=1,product=1,value=seq(1,20,0.5)), 
             data.frame(approach=1,product=2,value=seq(5,15,0.3)), 
             data.frame(approach=1,product=3,value=seq(5,17,0.2)), 
             data.frame(approach=2,product=1,value=seq(1,13,0.3)), 
             data.frame(approach=2,product=2,value=seq(3,18,0.5)), 
             data.frame(approach=2,product=3,value=seq(4,25,0.7)), 
             data.frame(approach=3,product=1,value=seq(1,15,0.6)), 
             data.frame(approach=3,product=2,value=seq(3,16,0.5)), 
             data.frame(approach=3,product=3,value=seq(1,10,0.1)))

dat$product<-as.factor(dat$product)

gg1<-ggplot(dat, aes(x =product, y = value)) +
  geom_boxplot() + 
  facet_grid(cols=vars(approach)) 


gt = ggplot_gtable(ggplot_build(gg1))
grid.draw(gt)

Solution

  • ggplot(dat, aes(x =product, y = value)) +
      geom_boxplot() + 
      coord_cartesian(xlim = c(1.2, 2, 2.8)) +
      facet_grid(cols=vars(approach))