Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot multiple Poisson distribution in one plot

Tags:

plot

r

ggplot2

I would like to plot multiple Poisson (with different lambdas (1:10))

I found the following function to draw a plot

plot_pois = function(lambda = 5)
{
  plot(0:20, dpois( x=0:20, lambda=lambda ), xlim=c(-2,20))
  normden <- function(x){dnorm(x, mean= lambda, sd=sqrt(lambda))}
  curve(normden, from=-4, to=20, add=TRUE, col=lambda)
}
plot.new()
plot_pois(2)

enter image description here

But I can't plot another Poisson over it. I tried to change plot to points or lines but it totally changes the plot. I would also like to add a legends containing different colors for different values of lambda.

If I could plot it using ggplot, it would be a better option.

like image 496
Ahmad Avatar asked Sep 09 '26 14:09

Ahmad


1 Answers

Another possible tidyverse solution:

library(tidyverse)

# Build Poisson distributions

p_dat <- map_df(1:10, ~ tibble(
  l = paste(.),
  x = 0:20,
  y = dpois(0:20, .)
))

# Build Normal distributions

n_dat <- map_df(1:10, ~ tibble(
  l = paste(.),
  x = seq(0, 20, by = 0.001),
  y = dnorm(seq(0, 20, by = 0.001), ., sqrt(.))
))

# Use ggplot2 to plot

ggplot(n_dat, aes(x, y, color = factor(l, levels = 1:10))) +
  geom_line() +
  geom_point(data = p_dat, aes(x, y, color = factor(l, levels = 1:10))) +
  labs(color = "Lambda:") +
  theme_minimal()

Created on 2019-05-06 by the reprex package (v0.2.1)

like image 54
tomasu Avatar answered Sep 11 '26 06:09

tomasu