Search code examples
rplotkernel-density

Plot kernel density estimation with the kernels over the individual observations in R


Well to keep things short what I want to achieve is a plot like the right one:

enter image description here

I would like to obtain a standard KDE plot with its individual kernels plotted over the observations.

The best solution would be the one that considers all the different kernel functions (e.g. rectangular, triangular etc).


Solution

  • Well after reading this Answer I managed to come up with an solution.

    # Create some input data
    x<-c(19, 20, 10, 17, 16, 13, 16, 10,  7, 18)
    
    
    # Calculate the KDE
    kde<-density(x,kernel="gaussian",bw=bw.SJ(x)*0.2)
    
    # Calcualte the singel kernels/pdf's making up the KDE of all observations
    A.kernel<-sapply(x, function(i) {density(i,kernel="gaussian",bw=kde$bw)},simplify=F)
    sapply(1:length(A.kernel), function(i){A.kernel[[i]][['y']]<<-(A.kernel[[i]][['y']])/length(x)},simplify=F)
    
    
    # Plot everything together ensuring the right scale (the area of the single kernels is corrected) 
    plot(kde)
    rug(x,col=2,lwd=2.5)
    sapply(A.kernel, function(i){
            lines(i,col="red")}
            )
    

    The result looks like this: enter image description here