如何在R中绘制1000个模拟

时间:2013-10-15 13:11:06

标签: r ggplot2

我已通过以下代码生成了1000次模拟。

ar1 = 0.4857
ar2 = 0.0173
ma1 = -0.8054
r0 <-  0.002937432 #mean of margin.logrtn
e0 <- 0.002976873 #mean of fit.margin.logrtn$res


r.sims <- matrix(rep(0,1000*52),nrow=52, ncol=1000)
e.sims <- matrix( rnorm(52*1000, mean =  0.002976873, sd = 0.1056021), 52, 1000) 


r.sims[1] <- ar1*r0 + e.sims[1] + ma1*e0
r.sims[2] <- ar1*r.sims[1] + ar2*r0 + e.sims[2] + ma1*e.sims[1]

for(j in 1:1000) {
    for(i in 1:52) {
        if (i == 1) {
            r.sims[i,] <- r.sims[1]
        } else {
            if(i == 2) {
                r.sims[i,] <- r.sims[2]
            } else {
                if(i > 2) {
                    r.sims[i,] <- r.sims[i-1,]*ar1 + r.sims[i-2,]*ar2 + e.sims[i,] + e.sims[i-1,]*ma1
                }
            }
        }
    }
}

我想绘制R中的模拟,我想创建模拟的每周日期,并在同一图表上绘制所有1000个模拟。我试图将数据导出到excel并在那里创建日期,然后再次导入数据,但后来我意识到我必须创建1000个时间序列,这是太多的输入...除非有更简单的方法来做到这一点..有人可以帮忙吗?

非常感谢!

1 个答案:

答案 0 :(得分:2)

你没有提到什么样的情节,所以这里只是一个简单的时间序列图。无论如何,你也可以在plot命令中使用for循环,除非我在你的问题中遗漏了一些东西。

ymax <- max(r.sims)
ymin <- min(r.sims)

plot(r.sims[,1], type="l", col="#ff000010", ylim=c(ymin, ymax))
for (i in 2:1000){
lines(r.sims[,i], type="l", col="#ff000010")
}

enter image description here


修改

问:嗨,我想知道是否有任何方式可以用多种颜色绘制这个?非常感谢!

A:是的,您可以通过提供一系列颜色代码来实现:

ymax <- max(r.sims)
ymin <- min(r.sims)
color <- c(rep("#ff000010", 499), rep("#0000ff10", 500))

plot(r.sims[,1], type="l", col="#ff000010", ylim=c(ymin, ymax))
for (i in 2:1000){
lines(r.sims[,i], type="l", col=color[i])
}

第三行指定第一个499为红色,下一个为500为蓝色。然后在最后一行中,添加“col = color [i]”以应用颜色方案。

enter image description here