简体   繁体   中英

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. 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

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 .

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM