Reputation: 23154
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.
Upvotes: 1
Views: 500
Reputation: 13310
Why not use geom_density?
ggplot(dat) +
geom_density(aes(x=res, color=as.factor(method)))
Upvotes: 1
Reputation: 98599
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")
Upvotes: 4