I don't think you can do this within ggplot
. You can calculate the density yourself and then plot the calculated density. Below I show that it actually works, by reproducing the plot you already have with ggplot(df,aes(size,color=habitat)) + geom_density(aes(y=..count..))
.
require(plyr)
# calculate the density
res <- dlply(df, .(habitat), function(x) density(x$size))
dd <- ldply(res, function(z){
data.frame(size = z[["x"]],
count = z[["y"]]*z[["n"]])
})
# these two plots are essentially the same.
ggplot(dd, aes(size, count, color=habitat)) +
geom_line()
ggplot(df,aes(size,color=habitat))+
geom_density(aes(y=..count..))
Now for the slightly more difficult task of averaging the densities of the different replicates.
# calculate the density
res <- dlply(df, .(habitat), function(dat){
lst <- dlply(dat, .(replicat), function(x) density(x$size,
# specify to and from based on dat, not x.
from=min(dat$size),
to=max(dat$size)
))
data.frame(size=lst[[1]][["x"]],
#count=colMeans(laply(lst, function(a) a[["y"]]), na.rm=TRUE)*nrow(dat),
count=colMeans(laply(lst, function(a) a[["y"]]), na.rm=TRUE)*nrow(dat)/nlevels(droplevels(dat$replicat)),
habitat=dat$habitat[1])
})
dd <- rbindlist(res)
ggplot(dd, aes(size, count, color=habitat)) +
geom_line()