You are using the ggboxplot
from ggpubr
which is based on ggplot2
, which is based on grid
graphics system. Unfortunately, grid
graphics does not work with base
R graphics, so setting par
doesn't work either. To arrange plots created by the library build on top of grid
please use the grid.arrange
from gridExtra
package. See the example below:
library(ggpubr)
data("ToothGrowth")
df <- ToothGrowth
grobsList <- list()
for (i in c(1:4)) {
p <- ggboxplot(df, x = "dose", y = "len", width = 0.8)
grobsList <- c(grobsList, list(p))
}
gridExtra::grid.arrange(
grobs = grobsList, ncol = 2, nrow = 2)
You can also try to use marrangeGrob
but it might create the plot outside the current graphical window.
You can also render the plots inside the loop when the desired number of plots were created:
library(ggpubr)
data("ToothGrowth")
df <- ToothGrowth
grobsList <- list()
for (i in c(1:7)) {
p <- ggboxplot(df, x = "dose", y = "len", width = 0.8)
grobsList <- c(grobsList, list(p))
if(length(grobsList) == 4) {
# print the result
gridExtra::grid.arrange(
grobs = grobsList, ncol = 2, nrow = 2)
grobsList <- list() # reset the list containing the plots
}
}
# print the remaining plots
if(length(grobsList) > 0) {
gridExtra::grid.arrange(
grobs = grobsList, ncol = 2, nrow = 2)
}