2

I have 8 plots (P1,P2,P3,P4,P5,P6,P7,P8) and for illustration purposes, I want to display them all together (that is, in a 3x3 graph). However, also for illustration purposes, I want to display P1 and P2 in the upper row, P3,P4 and P5 in the middle row, and P6,P7 andP8 in the lower row.

How can I arrange the plots in order to get that? I would like to leave the gap in the upper right corner for instance. So far, I've done this:

grid.arrange(P1,P2,P3,P4,P5,P6,P7,P8, ncol=3)

Does anyone know how to do it?

Ellen Spertus
  • 6,576
  • 9
  • 50
  • 101
Dekike
  • 1,264
  • 6
  • 17
  • 1
    I believe you can add a blank grob to your `grid.arrange` function. See [this question](https://stackoverflow.com/questions/20552226/make-one-panel-blank-in-ggplot2) answer by @Jaap – Mxblsdl Nov 15 '19 at 16:33

1 Answers1

3

You can use the layout_matrix option of grid.arrange. You just need to build a matrix where the value of each cell indicates which plot should be drawn in that portion of the matrix. Here's one example

# sample plots
library(ggplot2)
P <- lapply(1:8, function(i) ggplot(data.frame(x=1, y=1), aes(x,y)) + geom_text(label=i))

# create layout
m <- matrix(c(rep(1:2, each=3), rep(3:8, each=2)), ncol=6, byrow=TRUE)
grid.arrange(grobs=P, layout_matrix = m)

enter image description here

Since the matrix has to have a consistent number of rows and columns, we create one with 6 columns. We assign the top left three cells to plot 1, the top right three cells to plot 2, then on the rest of the rows, we assign two cells per plot.

# m
     [,1] [,2] [,3] [,4] [,5] [,6]
[1,]    1    1    1    2    2    2
[2,]    3    3    4    4    5    5
[3,]    6    6    7    7    8    8

If you just wanted a blank cell in one of the positions, you can use an NA in the layout matrix (and go back to using a 3x3 matrix since we don't need to match up two and three column rows)

m <- matrix(c(1,2,NA,3:8), ncol=3, byrow=TRUE)
grid.arrange(grobs=P, layout_matrix = m)

enter image description here

MrFlick
  • 195,160
  • 17
  • 277
  • 295