Adding a X axis when using grid arrange

5.3k views Asked by At

I am having a problem to increase the size and add a label for x axis when I use grid.arrange.

I asked a question here how can I make my data side by side barplot with dots which the answer is sufficient and I accepted it.

At the end of the code, I should glue three parts together like this

library(gridExtra) 
gg1 <- ggplot_gtable(ggplot_build(g1)) 
gg2 <- ggplot_gtable(ggplot_build(g2)) 
gg.mid <- ggplot_gtable(ggplot_build(g.mid)) 

grid.arrange(gg1,gg.mid,gg2,ncol=3,widths=c(4/9,1/9,4/9))

I want to add a Label for it but I could not find a way to do this. I also searched and I found only one related post Universal x axis label and legend at bottom using grid.arrange

and I tried to assigned my grid.arrangeto a variable and then

p <- grid.arrange(gg1,gg.mid,gg2,ncol=3,widths=c(4/9,1/9,4/9))
p <- arrangeGrob(p, textGrob("my label", gp=gpar(fontsize=12)))
print(p)

but the problem is not solved. Any idea how to add such a label for it?

1

There are 1 answers

9
baptiste On BEST ANSWER
g1 <- g.mid <- g2 <- ggplot()

grid.arrange(g1,g.mid,g2,ncol=3,widths=c(4/9,1/9,4/9), 
             bottom=textGrob("x axis title", gp=gpar(fontsize=22)))

enter image description here

Edit: perhaps the easiest way to control margins is to wrap the grob in a 3x3 gtable,

titleGrob <- function(label, margin=unit(c(b=5, l=0, t=2, r=0), "line"), ..., debug=FALSE){
  library(gtable)
  tg <- textGrob(label, ...)
  w <- grobWidth(tg)
  h <- grobHeight(tg)

  g <- gtable("title",
              widths = unit.c(margin[2], w, margin[4]), 
              heights = unit.c(margin[3], h, margin[1]), respect = FALSE)
  if(debug){
    rg <- rectGrob()
    pos <- expand.grid(x=1:3, y=1:3)[-5,]
    g <- gtable_add_grob(g, list(rg, rg, rg, rg, rg, rg, rg, rg), t=pos$y, l=pos$x)
  }
  gtable_add_grob(g, tg, t=2, l = 2)
}

grid.arrange(g1,g.mid,g2,ncol=3,widths=c(4/9,1/9,4/9),
             bottom=titleGrob("x axis title", gp=gpar(fontsize=22), debug=FALSE))

enter image description here