[英]How to save plots within a for loop in R
I have the following reproducible code which produces a series of graphs:我有以下可重现的代码,可生成一系列图表:
N <- 199
K <- N+1
x <- rep(0,N)
x[1] <- 0.5
time <- c(1:K)
G <- c(2.7, 2.9, 3.0, 3.5, 3.82, 3.83, 3.84, 3.85)
for (g in G) {
for (t in 1:N) {
x[t+1] = g*x[t]*(1-x[t])
}
plot(time,x, main = g, type="l", xlim=c(0,100), col="blue")
}
This produces 8 graphs and I want to save each as .png files.这会生成 8 个图形,我想将每个图形保存为 .png 文件。 I am trying to do something like:我正在尝试执行以下操作:
png("graph_", g, ".png")
plot(time, x, ...)
dev.off
between the end of the for(g in G)
and for(t in 1:N)
loops in the above code such that I create a series of files named: graph_2.7.png, graph_3.0.png, ... graph_3.85.png在上面代码中的for(g in G)
和for(t in 1:N)
循环的末尾之间,我创建了一系列名为:graph_2.7.png、graph_3.0.png、... graph_3.85.png
I am not sure if I need to create a list and paste each result into said list or slightly change my syntax我不确定是否需要创建一个列表并将每个结果粘贴到所述列表中或稍微更改我的语法
You were very close.你非常接近。 You need to paste
the filename together in png
.您需要将文件名paste
到png
。
N <- 199
K <- N+1
x <- rep(0,N)
x[1] <- 0.5
time <- c(1:K)
G <- c(2.7, 2.9, 3.0, 3.5, 3.82, 3.83, 3.84, 3.85)
for (g in G) {
for (t in 1:N) {
x[t+1] = g*x[t]*(1-x[t])
}
png(file = paste0("graph_", g, ".png"))
plot(time,x, main = g, type="l", xlim=c(0,100), col="blue")
dev.off()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.