How to overlay distribution curves on histograms using ggplot2 and a grid

Let's say I use facet_grid() in ggplot2 to get 2 histograms. Now I want to superimpose these histograms on the Poisson curves (having different means for two graphical plots / grids) and the second curve of a different distribution (for which I want to manually provide a probability function of values). How can this be done?

Building an example:

 library(ggplot2) value<-c(rpois(500,1.5)) group<-rep(c("A","B"),250) data<-data.frame(value,group) g1<-ggplot(data,aes(value)) g1+geom_histogram(aes(y=..count..),binwidth=1,position="identity")+facet_grid(.~group) 

What's next?

Alternatively, can this be done using a lattice package?

+4
source share
2 answers

A simple way is to overlay densities instead of counts and use stat_function ()

 library(ggplot2) value<-c(rpois(500,1.5)) group<-rep(c("A","B"),250) data<-data.frame(value,group) ggplot(data,aes(value)) + geom_histogram(aes(y=..density..), binwidth=1,position="identity") + facet_grid(.~group) + stat_function(geom = "line", fun = dpois, arg = list(lambda = 1.5), colour = "red", fill = NA, n = 9) 

If you want to count, then you need to convert dpois densities to "counts"

 ggplot(data,aes(value)) + geom_histogram(aes(y=..count..), binwidth=1,position="identity") + facet_grid(.~group) + stat_function(geom = "line", fun = function(..., total){dpois(...) * total}, arg = list(lambda = 1.5, total = 250), colour = "red", fill = NA, n = 9) 
+6
source

When you ran into a similar problem (comparing distributions), I wrote code for transparent overlapping histograms that might give you some ideas where to start.

+2
source

All Articles