用 R 中的单个观察值绘制核密度估计图

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

好吧,简而言之,我想要实现的是一个像正确的情节:

我想获得一个标准的 KDE 图,其各个内核绘制在观察结果上。

最好的解决方案是考虑所有不同内核函数(例如矩形、三角形等)的解决方案。

好吧,看完这篇文章后 Answer 我想出了一个解决方案。

# 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")}
        )

结果如下所示: