Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to display a list of multiple ggplots in a matrix

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 3×3 but none of them worked. The plots were displayed individually instead of in one page/window.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading