简体   繁体   中英

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:

在此处输入图片说明

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 (eg rectangular, triangular etc).

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: 在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM