簡體   English   中英

使用 R 和 ggplot2 模擬泊松過程

[英]Simulation Poisson Process using R and ggplot2

使用速率 lambda = 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))

我怎么能做到?

非常感謝!

我想你可以讓這更簡單。 這是一個ggplot解決方案。

首先,創建一個 function,它將通過使用適當的 lambda 從指數分布中抽取樣本來模擬泊松過程。 在此示例中,我使用了一個while循環,該循環以第一個元素為 0 的向量x開頭。 function 通過添加隨機樣本來增長該向量,直到其總和達到目標持續時間tmax 這不是最有效的方法,但應該使示例更清晰。

當達到目標時,function 返回向量的累積和,表示相應 lambda 的泊松過程的到達時間。 請注意,為了使繪圖更容易,它實際上返回一個數據幀,其中包含累積時間、累積計數和一個分組變量run ,這將允許我們在單個 plot 上輕松運行幾次 plot。

make_sample_df <- function(run, tmax, lambda)
{
  x <- 0
  while(sum(x) < tmax) x <- c(x, rexp(1, lambda))
  data.frame(t = cumsum(x), N = seq_along(x), run = rep(run, length(x)))
}

我們現在可以在實際繪圖 function 中使用這個 function:

plot_poisson <- function(runs, tmax, lambda)
{
  # Creates one data frame for each run, this sticks them all together:
  df <- do.call("rbind", lapply(seq(runs), make_sample_df, tmax, lambda))

  ggplot2::ggplot(df, aes(t, N, group = run)) + 
    geom_step(alpha = 0.25) + 
    labs( title = paste(runs, "runs of Poisson process with lambda", lambda)) +
    theme(legend.position = "none") +
    coord_cartesian(xlim = c(0, tmax))
}

所以你可以這樣做:

plot_poisson(runs = 10, tmax = 100, lambda = 0.7)

在此處輸入圖像描述

plot_poisson(runs = 100, tmax = 100, lambda = 0.7)

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM