I want to make multiple ggplot in a loop and show them on one plot.
for ( i in 1:8) {
g <- ggplot(data=mtcars, aes(x=hp, y=wt))+
geom_point()
print(g)
}
I want to arrange the plots above on one page, 4 rows and 2 columns. Does anyone know how to do that? Thanks.
We can put multiple graphs in a single plot by setting some graphical parameters with the help of par() function. R programming has a lot of graphical parameters which control the way our graphs are displayed. The par() function helps us in setting or inquiring about these parameters.
The function ggarrange() [ggpubr] provides a convenient solution to arrange multiple ggplots over multiple pages. After specifying the arguments nrow and ncol, ggarrange()` computes automatically the number of pages required to hold the list of the plots. It returns a list of arranged ggplots.
The base R functions such as par() and layout() will not work with ggplot2 because it uses a different graphics system and this system does not recognize base R functionality for plotting. However, there are multiple ways you can combine plots from ggplot2 . One way is using the cowplot package.
You can save all the plot in a list
then use either cowplot::plot_grid()
or gridExtra::marrangeGrob()
to put them in one or more pages
See also:
Creating arbitrary panes in ggplot2 (patchwork
, multipanelfigure
& egg
packages)
Multiple plots in for loop
library(tidyverse)
# create a list with a specific length
plot_lst <- vector("list", length = 8)
for (i in 1:8) {
g <- ggplot(data = mtcars, aes(x = hp, y = wt)) +
geom_point()
plot_lst[[i]] <- g
}
# Combine all plots
cowplot::plot_grid(plotlist = plot_lst, nrow = 4)
library(gridExtra)
ml1 <- marrangeGrob(plot_lst, nrow = 2, ncol = 2)
ml1
Created on 2018-09-20 by the reprex package (v0.2.1.9000)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With