简体   繁体   中英

R poisson fit in ggplot2

I have a data set of interarrival times between events. I used ggplot2 to make histograms of the interarrival times, and faceted by type of event. Visual evidence is strong that the interrival time is Poisson distributed. How can I easily fit a Poisson distribution to each group and overlay the Poisson density function on the histograms?

The ggh4x package has a function for fitting and plotting theoretical density functions using the fitdistrplus package. Note that Poisson is a discrete distribution, so the line can get a bit jagged. Disclaimer: I'm the author of the ggh4x package, so I'm biased.

library(ggplot2)
library(ggh4x)

set.seed(42)
df <- data.frame(
  x = c(rpois(50, 5), rpois(50, 10)),
  group = rep(c("A", "B"), each = 50)
)

ggplot(df, aes(x)) +
  geom_bar(aes(fill = group, y = after_stat(prop)),
           alpha = 0.5, width = 1, position = "identity") +
  stat_theodensity(aes(colour = group), distri = "pois")

Created on 2021-04-03 by the reprex package (v1.0.0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM