将模拟泊松分布添加到ggplot

时间:2014-05-18 18:42:23

标签: r ggplot2 plyr poisson

我进行了泊松回归,然后将模型可视化:

library(ggplot2)
year <- 1990:2010
count <- c(29, 8, 13, 3, 20, 14, 18, 15, 10, 19, 17, 18, 24, 47, 52, 24, 25, 24, 31, 56, 48)
df <- data.frame(year, count)
my_glm <- glm(count ~ year, family = "poisson", data = df)
my_glm$model$fitted <- predict(my_glm, type = "response")
ggplot(my_glm$model) + geom_point(aes(year, count)) + geom_line(aes(year, fitted))

enter image description here

现在我想将这些模拟泊松分布添加到图中:

library(plyr)
poisson_sim <- llply(my_glm$model$fitted, function(x) rpois(100, x))

情节看起来应该是这样的(红点是照片):

enter image description here

1 个答案:

答案 0 :(得分:4)

您可以将模拟值转换为矢量,然后使用它们创建新数据框,其中一列包含每100次重复的年份,第二列是模拟值。

poisson_sim <- unlist(llply(my_glm$model$fitted, function(x) rpois(100, x)))
df.new<-data.frame(year=rep(year,each=100),sim=poisson_sim)

然后使用geom_jitter()添加模拟点。

ggplot(my_glm$model) + geom_point(aes(year, count)) + geom_line(aes(year, fitted))+
      geom_jitter(data=df.new,aes(year,sim),color="red")

enter image description here