13

I'm using the grid package to display an array of plots like this:

layout <- grid.layout(2, 4)
pushViewport(viewport(layout = layout))
# print various plots

Is there some way to specify a title for the whole grid layout?

nccc
  • 1,095
  • 3
  • 11
  • 20

2 Answers2

20

Another way:

library(gridExtra)
g = rectGrob() # dummy "plot"
grid.arrange(g, g, g, g, ncol=2, top = "Main Title")
user20650
  • 24,654
  • 5
  • 56
  • 91
baptiste
  • 75,767
  • 19
  • 198
  • 294
  • Can you give an example that works with a somewhat formatted title? E.g. where the top parameter is not a text but a grob, how would that work? – mzuba Mar 14 '20 at 10:46
  • 1
    `grid.arrange(g, g, g, g, ncol=2, top = textGrob("Main Title",rot=90))` – baptiste Mar 16 '20 at 06:08
18

Dummy example based on a similar SO question: Place title of multiplot panel with ggplot2

  1. First create a layout with the required number of rows + 1 short one for title:

    pushViewport(viewport(layout = grid.layout(3, 2, heights = unit(c(0.5, 5, 5), "null"))))   
    
  2. Create some plots there:

    print(ggplot(mtcars, aes(hp)) + geom_histogram(), vp = viewport(layout.pos.row = 2, layout.pos.col = 1:2))
    print(ggplot(mtcars, aes(wt)) + geom_histogram(), vp = viewport(layout.pos.row = 3, layout.pos.col = 1))
    print(ggplot(mtcars, aes(mpg)) + geom_histogram(), vp = viewport(layout.pos.row = 3, layout.pos.col = 2))
    
  3. Add a title to the top row:

    grid.text("MAIN TITLE", vp = viewport(layout.pos.row = 1, layout.pos.col = 1:2))
    

Resulting in:

enter image description here

Community
  • 1
  • 1
daroczig
  • 28,004
  • 7
  • 90
  • 124
  • using a base plot is a little confusing; particularly since it doesn't respect the layout. – baptiste May 27 '12 at 19:50
  • Thanks a lot @baptiste, I have updated my answer based on your guidance (and `+1` for your answer and great package). – daroczig May 27 '12 at 20:08
  • The problem with this approach is that the title scales with the graphs. However, I'd like the title to have constant height as the window is resized or when I print to PDF. – nccc May 28 '12 at 19:24
  • 3
    just set the layout heights accordingly, e.g. `unit.c(unit(1, "line"), unit(rep(0.5, 2), "npc") - 0.5*unit(1, "line"))` – baptiste May 28 '12 at 19:50