简体   繁体   English

循环错误-plot.new尚未被调用

[英]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). 我模拟了22个交易日(1个起始值)的1000条路径。 Now I want to include it into my presentation, but animated, so I need the png files. 现在,我想将其包括在演示文稿中,但要进行动画处理,因此我需要png文件。

I want to create 1000 png files, starting with the first stock path, then the second and so on. 我想创建1000个png文件,从第一个股票路径开始,然后从第二个路径开始,依此类推。

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: 因此,我从第一个路径开始,在图上添加第二个,再添加第三个,依此类推,最后,我得到了一个包含1000个模拟的图,这是我的代码:

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. (我知道这不是一个可行的示例,但是我的问题只是循环中的一个逻辑问题)当我上一个代码:plot.new尚未被调用时,出现以下错误消息。

The matrix has 1000 columns and 23 row entries, this should be 1000 simulations of stock pathes for 22 trading days. 矩阵有1000列和23行条目,这应该是22个交易日内1000个股票路径的模拟。

How can I change that the error does not appear anymore? 如何更改该错误不再出现? Thanks! 谢谢!

Use two for loops. 使用两个for循环。 The outer loop will create each png/jpeg. 外循环将创建每个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()
}

jpeg and plot both make new graphs. jpegplot都创建了新图形。 You just need lines calls in the loop, if you want the animation to build and not erase. 如果您希望动画而不是擦除,则只需要循环中的lines调用即可。 One thing, lines doesn't need type = 'l' . 一件事, lines不需要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. 如果您想用它来绘制点,则可以更改参数,否则可以省去它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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