Q:

ggplot2 gets the density wrong?

Here is the code:
dat = data.frame(method=gl(3, 100), res=c(rnorm(100), rnorm(100, 1, 1), rnorm(100, 2, 1)))
png('/tmp/a.png')
p = ggplot(dat)
p = p + stat_density(aes(x=res, group=method, color=as.factor(method)), geom='line')
print(p)
dev.off()

png('/tmp/b.png')
res1 = dat[dat$method==1, ]
res2 = dat[dat$method==2, ]
res3 = dat[dat$method==3, ]
plot(density(res1))
lines(density(res2$res), col='green')
lines(density(res3$res), col='red')
dev.off()

Results:

One can see the second figure using plot() is correct.

A:

For the stat_density() default position is "stack" - so those three lines are stacked. To get the same result as in plot() use position="identity".
ggplot(dat)+ stat_density(aes(x=res, group=method, color=as.factor(method)), 
         geom='line',position="identity")

