Search code examples
rggplot2boxplotcowplot

How do I customize the margin and label settings with plot_grid?


I would like to have the title not be chopped off and have the axis labels removed from this chart that I generated with plot_grid from cowplot.enter image description here

Here is my code

    data(mtcars)
 library(ggplot2)
 library(cowplot)
 mpg = ggplot() +
 geom_boxplot(aes(y = mpg,x = as.factor(cyl)),data=mtcars) +
 coord_flip()
 am=ggplot() +
 geom_boxplot(aes(y = mpg,x = as.factor(am)),data=mtcars) +
 coord_flip()
 vs=ggplot() +
 geom_boxplot(aes(y = mpg,x = as.factor(vs)),data=mtcars) +
 coord_flip()
 gear = ggplot() +
 geom_boxplot(aes(y = mpg,x = as.factor(gear)),data=mtcars) +
 coord_flip()
 p=plot_grid(mpg,am,vs,gear, labels = "Variables effecting Mileage", label_size = 14, hjust = -0.5,
 + vjust = 0.5)+theme_grey()
p

Also, if it would be simpler to create this without cowplot, what do you suggest?


Solution

  • Here is a cowplot only answer. It might be more what you want.

    library(ggplot2)
    library(cowplot)
    library(gtable)
    
    data(mtcars)
    
    mpg = ggplot() +
      geom_boxplot(aes(y = mpg,x = as.factor(cyl)),data=mtcars) +
      coord_flip() + labs(x="",y="")
    am=ggplot() +
      geom_boxplot(aes(y = mpg,x = as.factor(am)),data=mtcars) +
      coord_flip()+ labs(x="",y="")
    vs=ggplot() +
      geom_boxplot(aes(y = mpg,x = as.factor(vs)),data=mtcars) +
      coord_flip()+ labs(x="",y="")
    gear = ggplot() +
      geom_boxplot(aes(y = mpg,x = as.factor(gear)),data=mtcars) +
      coord_flip()+ labs(x="",y="")
    p=plot_grid(mpg,am,vs,gear) +
      theme_grey() +
    
    # Use annotation text as it is centered at the x,y point
      annotate("text",x=0.5,y=1.04,size=7,label="Variables affecting Mileage") +
    
    # Add some space around the edges  
      theme(plot.margin = unit(c(1,0.5,0.5,0.5), "cm")) 
    
    
    # Suppress tick marks
    p=p+scale_y_continuous(breaks=NULL)+scale_x_continuous(breaks=NULL)
    
    # Have to turn off clipping
    gt <- ggplot_gtable(ggplot_build(p))
    gt$layout$clip[gt$layout$name == "panel"] <- "off"
    
    # need to draw it with the new clip settings
    grid.draw(gt)
    

    Yields:

    enter image description here