使用R和ggplot2的模拟泊松过程

问题描述 投票:0回答:1

使用λ= 0.7的泊松过程的模拟。在纵轴上显示N(​​t),在横轴上显示时间t的泊松过程的样本运行。模拟范围为t [0:100]。生成具有10条轨迹的第一张图和具有100条轨迹的第二张图。

我已经尝试了以下代码,但是无法生成两个图形。

library(plyr)
library(ggplot2)

Process_poisson<- function(t, lambda){
distr_poisson<- rpois(1, t*lambda)
s_poisson<- sort(runif(distr_poisson, 0, t))
data.frame(x = c(0, 0, s_poisson),y = c(0, 0:distr_poisson))
}

N_simulations<- function(n,t,lambda){
s_poisson<- lapply (1:n, function(n) data.frame(Process_poisson(t, lambda), simulation = n))
s_poisson<- ldply (s_poisson, data.frame)
s_poisson$simulation<- factor(s_poisson$simulation)
}

t<- 0:100
lambda<- 0.7
N_simulations(10, t, lambda)
N_simulations(100, t, lambda)

par(mfrow = c(1,2))

matplot(x, y, type = "l", lty = 0:5, lwd = 1, lend = par("lend"),
     pch = NULL, col = simulation, cex = 0.5, bg = NA, main =sprintf("Nº simulations of trajectories of Poisson Process",10,lambda), xlab = "Time", ylab = "N(t)",
   xlim = c(0,100), ylim = c(-10,0))

matplot(Proceso_poisson(t, lambda), n, y, type = "l", lty = 0:5, lwd = 1, lend = par("lend"),
     pch = NULL, col = simulacion, cex = 0.5, bg = NA, main =sprintf("Nº simulations of trajectories of Poisson Process",10,lambda), xlab = "Time", ylab = "N(t)",
     xlim = c(0,100), ylim = c(-10,0))

我该怎么办?

非常感谢!

r simulation montecarlo poisson
1个回答
0
投票

我认为您可以简化很多。尚不清楚您是否希望计数是累积的(我想是的)。

这是一个ggplot解决方案:

plot_poisson <- function(runs, n, lambda)
{
  df <- data.frame(count = do.call("c", lapply(seq(runs), function(x) cumsum(rpois(n, lambda)))),
                   step = rep(seq(n), runs), 
                   run = factor(rep(seq(runs), each = n)))
  ggplot2::ggplot(df, aes(step, count, colour = run)) + geom_step()
}

因此您可以这样做:

plot_poisson(10, 100, 0.7)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.