R: Overlay Poisson distribution over histogram of data

与世无争的帅哥 提交于 2021-02-11 13:44:15

问题


I have some discrete data, which I have plotted in a histogram. I'd like to overlay a Poisson distribution to show the data is roughly Poisson distributed. Imagine the two plots from the code below merging into one plot, that is what I'd like to achieve.

# Read data
data <- read.csv("data.csv")

# Plot data
hist(data, prob=TRUE)

# Plot Poisson
c <- c(0:7)
plot(c, dpois(c, mean(data)), type="l")

I have tried the curve function:

curve(c, dpois(x=c, lambda=mean(data)), add=T)

But all I get is this:

The Poisson curve just seems to abruptly stop, but I would expect it to follow the shape of the histogram.

I'd like it to look like this (not necessarily with colours or multiple data sets):


回答1:


The code below does what you want.

set.seed(12111978)
vec <- rpois(50, 3)
hist(vec, prob=TRUE, ylim = c(0, .25)) # may need to tweak the y axis.
lines(0:max(vec), dpois(0:max(vec), mean(vec)), col = 'red')



来源:https://stackoverflow.com/questions/54112224/r-overlay-poisson-distribution-over-histogram-of-data

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