2

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

Brennan
  • 419
  • 5
  • 17

1 Answers1

3

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()
}
Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
  • _n.b._ when plotting multiple objects (like 2 or more DFs or similar), store them in a [list](https://stackoverflow.com/questions/28023427/applying-some-functions-to-multiple-objects) and then [lapply](https://stackoverflow.com/questions/54412460/r-using-lapply-to-save-plots) a function over them. – Ndharwood Feb 21 '22 at 19:29