Shading a kernel density plot between two points.

前端 未结 5 1482
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-22 06:59

I frequently use kernel density plots to illustrate distributions. These are easy and fast to create in R like so:

set.seed(1)
draws <- rnorm(100)^2
dens          


        
5条回答
  •  被撕碎了的回忆
    2020-11-22 07:12

    An expanded solution:

    If you wanted to shade both tails (copy & paste of Dirk's code) and use known x values:

    set.seed(1)
    draws <- rnorm(100)^2
    dens <- density(draws)
    plot(dens)
    
    q2     <- 2
    q65    <- 6.5
    qn08   <- -0.8
    qn02   <- -0.2
    
    x1 <- min(which(dens$x >= q2))  
    x2 <- max(which(dens$x <  q65))
    x3 <- min(which(dens$x >= qn08))  
    x4 <- max(which(dens$x <  qn02))
    
    with(dens, polygon(x=c(x[c(x1,x1:x2,x2)]), y= c(0, y[x1:x2], 0), col="gray"))
    with(dens, polygon(x=c(x[c(x3,x3:x4,x4)]), y= c(0, y[x3:x4], 0), col="gray"))
    

    Result:

    2-tailed poly

提交回复
热议问题