我不知道为什么会显示图形设备,但我可以指出您代码中的一些问题并提出替代方法。
您的代码返回 NULL 而不是存储图。需要使用下面的方式(很麻烦)来存储一个plot对象:
# 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
假设我们设法存储了 11 个图,marrangeGrob(pl, nrow = 2, ncol = 2) 命令尝试排列 4 个对象(2 行 x 2 列)。您需要摆脱 nrow=2 或 ncol=2。
我的建议是使用ggplot2 与grid.arrange 协作获得更灵活和优雅的绘图,这不会打开额外的图形窗口:
# 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)