我正在循环内工作,我想将绘图保存在列表中,以便我可以将它们一起绘制在 .pdf 中。问题在于列表未正确填充并使用上次运行的结果重新更新。所以,最终我得到的是一个包含五个完全相同的元素的列表。
我知道这些循环可能看起来毫无用处,但我只是让它们创建一个尽可能接近真实代码的测试代码(带有可重现的错误)。所以,我需要让循环保持原样。
library (ggplot)
library (gridExtra)
plist <- list()
for (z in 1:5){
n <- 100
k <- seq(0, to=4500+z*2000, length=n)
tmp <- numeric(n)
for (i in 1:n){
tmp[i] <- (5*(i*3)^2)}
plist[[z]] <- ggplot() +
geom_line(aes(x = k, y = tmp)) +
theme_bw()
pdf(sprintf("p%s.pdf", z),
width = 6, height = 4, onefile = T)
plot(plist[[z]])
dev.off()
}
do.call(grid.arrange, c(plist, ncol = 5))
这个答案基于:将绘图对象存储在列表中
library(ggplot2)
library(gridExtra)
plist <- list()
for (z in 1:5){
n <- 100
k <- seq(0, to=4500+z*2000, length=n)
tmp <- numeric(n)
for (i in 1:n){
tmp[i] <- (5*(i*3)^2)}
data <- data.frame(n, k, tmp)
plist[[z]] <- ggplot(data = data) + #data needs to be given!!
geom_line(aes(x = k, y = tmp)) +
theme_bw()
pdf(sprintf("p%s.pdf", z),
width = 6, height = 4, onefile = T)
plot(plist[[z]])
dev.off()
}
do.call(grid.arrange, c(plist, ncol = 5))
![enter image description here](https://i.stack.imgur.com/BNI3P.jpg)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)