2013-02-13 68 views
3

我有一些數據dt = data.table(x=c(1:200),y=rnorm(200)),我開始使用ggplot2密度的情節:增加百分線的密度圖

plot = ggplot(dt,aes(y)) + geom_density(aes(y=..density..)) 

有沒有一種方法,我可以添加類似this百分線?

如果再我能遮蔭的圖形類似this(按百分線創建)的片段,那麼這將是偉大的!

回答

4
myd = data.frame(xvar=rnorm(2000),yvar=rnorm(2000)) 

    xd <- data.frame(density(myd$xvar)[c("x", "y")]) 
    p <- ggplot(xd, aes(x, y)) + 

     geom_area(data = subset(xd, x < -1), fill = "pink") + 
     geom_area(data = subset(xd, x < -1.96), fill = "red") + 
     geom_area(data = subset(xd, x > 1), fill = "lightgreen") + 
     geom_area(data = subset(xd, x > 1.96), fill = "green") + 

     geom_line() 

    p 

enter image description here

9

下面是this answer很大程度上激發了可能性:

dt <- data.table(x=c(1:200),y=rnorm(200)) 
dens <- density(dt$y) 
df <- data.frame(x=dens$x, y=dens$y) 
probs <- c(0.1, 0.25, 0.5, 0.75, 0.9) 
quantiles <- quantile(dt$y, prob=probs) 
df$quant <- factor(findInterval(df$x,quantiles)) 
ggplot(df, aes(x,y)) + geom_line() + geom_ribbon(aes(ymin=0, ymax=y, fill=quant)) + scale_x_continuous(breaks=quantiles) + scale_fill_brewer(guide="none") 

enter image description here