2013-10-28 93 views
1

下面是代碼:ggplot2獲取密度錯誤?

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() 

結果:

enter image description here enter image description here

人們可以看到使用plot()是正確的第二個數字。

回答

4

對於stat_density()默認位置是"stack" - 所以這三條線是堆疊的。要得到與plot()相同的結果,請使用position="identity"

ggplot(dat)+ stat_density(aes(x=res, group=method, color=as.factor(method)), 
     geom='line',position="identity") 

enter image description here

1

爲什麼不使用geom_density?

ggplot(dat) + 
    geom_density(aes(x=res, color=as.factor(method)))