8
library( ggplot2 )
library( gridExtra )
p1 <- qplot( rnorm( 10 ), rnorm( 10 ) )
p2 <- qplot( rnorm( 10 ), rnorm( 10 ) )
p3 <- qplot( rnorm( 10 ), rnorm( 10 ) )
p4 <- qplot( rnorm( 10 ), rnorm( 10 ) )
p5 <- qplot( rnorm( 10 ), rnorm( 10 ) )
grid.arrange( p1, p2, p3, p4, p5, nrow=2 )

I would like to center the bottom two plots. How can do this? I can do it using split.screen but I'm unable to figure out how to do this with ggplot2. ggplot2 has cooler graphics.

Thanks in advance!

PK

12

You could use the gtable package for flexible and convenient grid layouts, or simply nest two arrangeGrobs,

ng = nullGrob()
grid.arrange(arrangeGrob(p1, p2, p3, nrow=1),
             arrangeGrob(ng, p4, p5, ng, nrow=1, widths=c(0.5, 1, 1, 0.5)),
             nrow=2)

enter image description here


Edit: For the bottom plots to span the full width, you simply need to remove the dummy nullGrobs() in the above solution:

grid.arrange(arrangeGrob(p1, p2, p3, nrow=1),
             arrangeGrob(p4, p5, nrow=1),
             nrow=2)

enter image description here

| improve this answer | |
  • 1
    Loved the answer but would be interested in seeing the gtable answer you discussed as well. +1 – Tyler Rinker May 28 '13 at 17:35
  • Thanks. What would be better was if the bottom plots filled the space. – polarise May 28 '13 at 17:50
7

Here's an alternative way using gtable:

library(gtable)
gtable_add_grobs <- gtable_add_grob #misleading name

g <- gtable(widths = unit(rep(1, 6), "null"), # need lcm(3,2)=6 for the matrix rows
            heights = unit(rep(1, 2), "null"))

#gtable_show_layout(g)

g <- gtable_add_grobs(g, lapply(list(p1, p2, p3, p4, p5), ggplotGrob),
                     t = c(1, 1, 1, 2, 2),
                     l = c(1, 3, 5, 2, 4),
                     r = c(2, 4, 6, 3, 5))

grid.newpage()
grid.draw(g)

Edit: For the bottom plots to span the full width, you simply need to alter the corresponding l and r indices,

g <- gtable_add_grobs(g, lapply(list(p1, p2, p3, p4, p5), ggplotGrob),
                      t = c(1, 1, 1, 2, 2),
                      l = c(1, 3, 5, 1, 4),
                      r = c(2, 4, 6, 3, 6))
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.