tags:

views:

107

answers:

2

Say, I am using facet_grid() in ggplot2 to obtain 2 histograms. Now I want to superimpose these histograms with Poisson curves (having different means for the 2 histogram plots/grids) and a second curve of another distribution (for which I want to manually provide the probability function of values). How can this be done?

constructing 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 next?

Alternatively, can it be done using the lattice package?

+1  A: 

The easy way is to plot 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 counts then you need to convert the densities of dpois 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)
Thierry
A: 

When recently faced with a similar problem (comparing distributions), I wrote up some code for transparent overlapping histograms that might give you some ideas on where to start.

chrisamiller