Shading a kernel density plot between two points.

前端 未结 5 1420
佛祖请我去吃肉
佛祖请我去吃肉 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:21

    This question needs a lattice answer. Here's a very basic one, simply adapting the method employed by Dirk and others:

    #Set up the data
    set.seed(1)
    draws <- rnorm(100)^2
    dens <- density(draws)
    
    #Put in a simple data frame   
    d <- data.frame(x = dens$x, y = dens$y)
    
    #Define a custom panel function;
    # Options like color don't need to be hard coded    
    shadePanel <- function(x,y,shadeLims){
        panel.lines(x,y)
        m1 <- min(which(x >= shadeLims[1]))
        m2 <- max(which(x <= shadeLims[2]))
        tmp <- data.frame(x1 = x[c(m1,m1:m2,m2)], y1 = c(0,y[m1:m2],0))
        panel.polygon(tmp$x1,tmp$y1,col = "blue")
    }
    
    #Plot
    xyplot(y~x,data = d, panel = shadePanel, shadeLims = c(1,3))
    

    enter image description here

提交回复
热议问题