不使用 density() 在 R 中分层密度图

Layering density plots in R without using density()

我使用 KernSmooth 包计算并绘制了高斯核密度估计值,如下所示:

 x <- MyData$MyNumericVector
 h <- dpik(x)
 est <- bkde(x, bandwidth=h)
 plot(est, type='l')

这是KernSmooth 文档中描述的方法。请注意,dpik() 找到最佳带宽,bkde() 使用此带宽来拟合核密度估计。重要的是我使用此方法而不是基本的 density() 函数。

如何将这些图叠加在一起?

我无法使用 ggplot2 中的 geom_density() 所依赖的基本 density() 函数,因为使用 KernSmooth 包可以对带宽和内核密度估计进行最佳优化(参见 Deng & Wickham, 2011 年在这里:http://vita.had.co.nz/papers/density-estimation.pdf)。由于 Wickham 写了 ggplot2 和上面对内核密度估计包的评论,所以有一种方法可以使用 ggplot2 来分层不依赖于基本 density() 函数的密度, 但我不确定。

即使我不想使用基本的 density() 功能,我可以为此使用 ggplot2 吗? lattice 呢?

你可以用 geom_line:

 m <- ggplot(NULL, aes(x=bkde(movies$votes)$x,y=bkde(movies$votes)$y)) + geom_line()
 print(m)

如果您使用 lattice::densityplot 进行操作,您可能可以将一些值添加到拖动列表中:

darg
list of arguments to be passed to the density function. Typically, this should be a list with zero or more of the following components : bw, adjust, kernel, window, width, give.Rkern, n, from, to, cut, na.rm (see density for details)