Search code examples
rggplot2poisson

Poisson density curve, histogram and shaded area with ggplot2?


How to make:

  1. a density curve and histogram displaying a poisson distribution with lambda = 2.5; and
  2. a density curve with shaded area showing P(X >= 4 with lambda = 2.5)

the x axis should be 0 to 10


Solution

  • Poisson distribution is a discrete probability distribution (function is defined only at integer values). So instead of a line it is better represented with points at integer values. To color a specific range under a function one can use geom = "area" and xlim = c(min(range), max(range):

    ggplot(data.frame(x = 0:10), aes(x)) +
      stat_function(geom = "point", n = 11, fun = dpois, args = list(lambda = 2.5)) +
      stat_function(geom = "area", aes(x), n = 7, fun = dpois, args = list(lambda = 2.5), xlim = c(4,10), fill = "lightblue", alpha = 0.5)+
      theme_bw()+
      scale_x_continuous(breaks = 0:10)
    

    enter image description here

    If the n argument in stat_function does not match the number of integer values over a range the plot is going to look funky.