I don't know why the graphics device is showing up but I can point out some issues in your code and suggest an alternative way.
Your code returns NULL
rather than storing the plots. You need to use the following approach (which is very troublesome) to store a plot
object:
# set seed for reproducibility
set.seed(147)
plot.new() # clears the previous plots
plot(1:10, rnorm(10), main = "test") # creates a scatter plot
p <- recordPlot() # stores the plot
p # accesses the plot
Let's say we managed to store 11 plots, the marrangeGrob(pl, nrow = 2, ncol = 2)
command tries to arrange 4 objects (2 rows x 2 columns). You need to get rid of either nrow=2
or ncol=2
.
My suggestion would be to use ggplot2
for more flexible and elegant plots in collaboration with grid.arrange
, which doesn't open up the extra graphics window:
# import packages
library(ggplot2)
library(gridExtra) # for grid.arrange
# simple wrapper to create multiple plots
my_ggplot <- function(no, x = 1:10, y = rnorm(10)) {
ggplot(mapping = aes(x, y)) +
geom_point() +
labs(title = paste("MY GGPLOT", no), x = "x-axis label", y = "y-axis label")
}
# build and store the plots
p1 <- my_ggplot(1)
p2 <- my_ggplot(2)
p3 <- my_ggplot(3)
p4 <- my_ggplot(4)
# arrange the plots in a grid with 2 colums
grid.arrange(p1, p2, p3, p4, ncol = 2)