rggplot2gridextra

gridExtra::marrange(): order plots by row


Given:

library(ggplot2)
l <- list(1:6)
for(i in 1:6){
  l[[i]] <- ggplot(data=data.frame(x=1:10, y=1:10)) +
    geom_point(aes(x=x, y=y)) +
    ggtitle(i)
}
ml <- marrangeGrob(l, nrow=3, ncol=2)
ml

I get the plots ordered by column, that is:
1 4
2 5
3 6

but I want them arranged by row:
1 2
3 4
5 6

I've tried with byrow=TRUE, but it has no effect. How could I arrange the plots by row?


Solution

  • As already suggested in the comments you can specify the order via the layout_matrix= argument, i.e. use the byrow = TRUE argument of matrix().

    Note: I switched to lapply to create the list of charts.

    library(ggplot2)
    library(gridExtra)
    
    l <- lapply(1:6, \(i) {
      ggplot(data = data.frame(x = 1:10, y = 1:10)) +
        geom_point(aes(x = x, y = y)) +
        ggtitle(i)
    })
    
    ml <- marrangeGrob(l,
      layout_matrix = matrix(
        seq_len(3 * 2),
        nrow = 3, ncol = 2,
        byrow = TRUE
      )
    )
    
    ml
    

    enter image description here