3

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?

0

1 Answer 1

4
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

Sign up to request clarification or add additional context in comments.

9 Comments

thanks! I liked and accepted your answer. I have one question, do you know how to also change the font and make them bold (the x axis values) ?
sounds like a different question, but have a look at axis.text.x in ?theme
sure thanks , one more stupid question. is it possible to make distance between the label you created and the figure?
thanks I already liked your answer so I cannot like it again. but one question. how can I remove those boxes and change the space? when I use your code, I just create the distance but I add those boxes. Sorry if I ask a lot of question
try changing the margin parameter and setting debug=FALSE
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.