Shade (fill or color) area under density curve by quantile

前端 未结 2 893
旧时难觅i
旧时难觅i 2020-12-15 09:24

Suppose e.g. I want to shade the area under the density curve for the standard normal distribution by decile. I want the left-most 10% of the area to have a differ

相关标签:
2条回答
  • 2020-12-15 09:47

    Something that works and could generalise:

    require(ggplot2)
    g <- ggplot(z.df, aes(x=x, y=pdf, fill=decile)) +
        scale_fill_gradient2(midpoint=5.5, guide="none") +
        theme_bw()
    for(n in 1:10) {
        g <- g + geom_ribbon(data=z.df[z.df$decile == n,], aes(ymin=0, ymax=pdf), colour = "black")
    }
    print(g)
    

    I don't find this particularly satisfactory since (1) I have to add a ribbon for each decile, and (2) if I'm using a for loop in R I'm usually doing something wrong.

    But the plot it gives is reasonable:

    Normal distribution curve with shaded deciles

    0 讨论(0)
  • 2020-12-15 09:55

    Actually aesthetics can vary with geom_ribbon(...) (or geom_area(...), which is basically the same thing), as long as you set the group aesthetic as well.

    delta     <- 0.001 
    quantiles <- 10
    z.df     <- data.frame(x = seq(from=-3, to=3, by=delta))
    z.df$pdf <- dnorm(z.df$x)
    z.df$qt  <- cut(pnorm(z.df$x),breaks=quantiles,labels=F)
    
    library(ggplot2)
    ggplot(z.df,aes(x=x,y=pdf))+
      geom_area(aes(x=x,y=pdf,group=qt,fill=qt),color="black")+
      scale_fill_gradient2(midpoint=median(unique(z.df$qt)), guide="none") +
      theme_bw()
    

    Setting quantiles <- 20 at the beginning produces this:

    0 讨论(0)
提交回复
热议问题