我希望它在单个页面上有 4 个图,而不是每页只有 1 个图,有没有办法可以使用循环中的 ggarrange 在单个页面上有 4 个不同的图?
library(ggplot2)
n <- 10 # number of plots
x <- rnorm(50, mean = 20)
y <- 2*x + 1 + rnorm(50)
df <- data.frame(x = x, y = y)
pdf("test.pdf", onefile = TRUE)
for(i in seq(n)){
df$x <- df$x + rnorm(50, sd = 0.01)
df$y <- df$y + rnorm(50, sd = 0.01)
p <- ggplot(data = df) + aes(x, y) +
geom_point()
print(p)
}
dev.off() # close device
最佳答案
你可以试试这个 -
# number of plots
n <- 10
#Create a dataframe
x <- rnorm(50, mean = 20)
y <- 2*x + 1 + rnorm(50)
df <- data.frame(x = x, y = y)
pdf("test.pdf", onefile = TRUE)
#for n = 10, loop will run 3 times.
#It will generate 4, 4, and 2 plots
for(i in seq(ceiling(n/4))) {
#For the last page
if(n > 4) k <- 4 else k <- n
n <- n - 4
#Create a list to store the plots
plot_list <- vector('list', k)
for(j in 1:k) {
df$x <- df$x + rnorm(50, sd = 0.01)
df$y <- df$y + rnorm(50, sd = 0.01)
plot_list[[j]] <- ggplot(data = df) + aes(x, y) + geom_point()
}
#Print multiple plots together
print(do.call(gridExtra::grid.arrange, plot_list))
}
dev.off()
关于r - 页面上的多个绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68419243/