Search code examples
rggplot2plotgraphpoisson

R: Overlay Poisson distribution over histogram of data


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.

Attempt at overlaying Poisson distribution

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


Solution

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

    Poisson distribution represented with lines