简体   繁体   English

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

[英]Layering density plots in R without using density()

I've computed and plotted gaussian kernel density estimates using the KernSmooth package as follows: 我已经使用KernSmooth软件包计算并绘制了高斯核密度估计值,如下所示:

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

This is the method described in KernSmooth's documentation. 这是KernSmooth文档中描述的方法。 Note that dpik() finds the optimal bandwidth and bkde() uses this bandwidth to fit the kernel density estimate. 请注意, dpik()找到最佳带宽,而bkde()使用该带宽来拟合内核密度估计。 It's important that I use this method instead of the basic density() function. 重要的是,我使用此方法代替基本的density()函数。

How do I layer these plots on top of one another? 如何将这些地块彼此叠加?

I cannot use the basic density() function that geom_density() from ggplot2 relies upon, as bandwidths and kernel density estimates are best optimized using the KernSmooth package (see Deng & Wickham, 2011 here: http://vita.had.co.nz/papers/density-estimation.pdf ). 我无法使用geom_density() ggplot2依赖的基本density()函数,因为带宽和内核密度估计值是使用KernSmooth软件包进行最佳优化的(请参见Deng&Wickham,2011,这里: http ://vita.had.co 。 nz / papers / density-estimation.pdf )。 Since Wickham wrote ggplot2 and the above review of kernel density estimation packages, it would make sense that there's a way to use ggplot2 to layer densities that aren't reliant on the basic density() function, but I'm not sure. 由于Wickham编写了ggplot2以及上面对内核密度估计软件包的回顾,因此,有一种方法可以使用ggplot2来分层不依赖于基本density()函数的density() ,但是我不确定。

Can I use ggplot2 for this even if I don't wish to use the basic density() function? 即使我不想使用基本的density()函数,我也可以使用ggplot2吗? What about lattice ? lattice

You could do it with geom_line : 您可以使用geom_line来做到这geom_line

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

If you were doing t with lattice::densityplot, you could probably add some of the values to the drags-list: 如果您正在使用grid :: densityplot做t,则可能会将一些值添加到drags-list中:

darg 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) 通常,这应该是一个包含零个或多个以下成分的列表:bw,adjust,kernel,window,width,give.Rkern,n,从,至,cut,na.rm(有关详细信息,请参见密度)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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