Add simulated poisson distributions to a ggplot

限于喜欢 提交于 2019-12-10 15:53:50

问题


I have made a poisson regression and then visualised the model:

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))

Now I want to add these simulated Poisson distributions to the plot:

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

The plot should look something like this (red points are photoshopped):


回答1:


You can convert simulated values to vector and then use them to make new data frame where one column contains years repeated each 100 times and second column is simulated values.

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)

Then add simulated points with 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")



来源:https://stackoverflow.com/questions/23725555/add-simulated-poisson-distributions-to-a-ggplot

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!