user1690846
user1690846

Reputation: 255

loop error - plot.new has not been called yet

I want to simulate stock paths. I have simulated 1000 paths with 22 trading days (1 starting value). Now I want to include it into my presentation, but animated, so I need the png files.

I want to create 1000 png files, starting with the first stock path, then the second and so on.

So I start with the first path, add a second to the plot, add the third and so on, so at the end I have a plot with 1000 simulations, here is my code:

for(i in 1:1000){
#jpeg(paste("1000s",i,".png",sep=""))
plot(c(1:23),matrix[,1],type="l",ylim=c(17,24))
lines(c(1:23),matrix[,i],type="l",col=i)
#dev.off()
}

Here is the problem, that each additional part disappears when the loop gets to the next value, so I tried:

plot(0,0 , xlim=c(1,23),ylim=c(17,24),xlab="",ylab="")
for(i in 1:1000){
jpeg(paste("1000s",i,".png",sep=""))
lines(c(1:23),matrix[,i],type="l",col=i)
dev.off()
}

(I know this is not a working example, but my problem is just a logical one with the loop) I get the following error message when I the last code: plot.new has not been called yet.

The matrix has 1000 columns and 23 row entries, this should be 1000 simulations of stock pathes for 22 trading days.

How can I change that the error does not appear anymore? Thanks!

Upvotes: 1

Views: 1161

Answers (2)

Erik Shilts
Erik Shilts

Reputation: 4509

Use two for loops. The outer loop will create each png/jpeg. The inner one will build up each individual plot.

for(i in 1:1000) {
  jpeg(paste("1000s", i, ".png", sep=""))
  plot(0, 0, xlim=c(1,23), ylim=c(17,24), xlab="", ylab="")

  for(j in 1:i) {
    lines(c(1:23), matrix[, j], col=j)
  } 
  dev.off()
}

Upvotes: 1

John
John

Reputation: 23768

jpeg and plot both make new graphs. You just need lines calls in the loop, if you want the animation to build and not erase. One thing, lines doesn't need type = 'l'. That's it's default and the whole point of the command is that's it's default. If you wanted to plot points with it you might change the argument but otherwise just leave it out.

Upvotes: 0

Related Questions