Home > Enterprise >  How to display a list of multiple ggplots in a matrix
How to display a list of multiple ggplots in a matrix

Time:11-12

I have an object myplots that contains 9 geom_point geom_smooth as shown below

enter image description here

I tried both approaches par(mfrow=c(3,3)) and layout(matrix(c(1, 2, 3, 4, 5, 6, 7, 8, 9), 3, 3, byrow=TRUE)) to display them in a grid of 3x3 but none of them worked. The plots were displayed individually instead of in one page/window.

What did I do wrong and how to solve the problem?

CodePudding user response:

One approach would to be use the cowplot package. The function cowplot::plot_grid() makes it very easy to do this sort of thing. Just pass your list of plots to the plotlist argument, and specify the nrow and/or ncol argument to choose how you want to arrange them. There's so much that can be done with this package and its much easier than base graphics, so I recommend using it, unless you are worried about adding another dependency to your code.

Here's an example I work up below:

library(ggplot2)
library(cowplot)

df <- data.frame(x = rnorm(20), y = rnorm(20))
x <- ggplot(df, aes(x = x, y = y))   geom_smooth()
l <- rep(list(x), 9)

plot_grid(plotlist = l, nrow = 3)

enter image description here

  • Related