r - 如何获得特定点的核密度估计值?

标签 r kernel-density

我正在尝试处理 R 中过度绘制的方法,我想尝试的一件事是绘制单个点,但根据其邻域的密度为它们着色。为了做到这一点,我需要计算每个点的 2D 核密度估计。然而,标准的核密度估计函数似乎都是基于网格的。是否有用于在我指定的特定点计算 2D 核密度估计的函数?我会想象一个函数,它将 x 和 y 向量作为参数并返回一个密度估计向量。

最佳答案

如果我了解您想要做什么,可以通过将平滑模型拟合到网格密度估计值,然后使用它来预测您感兴趣的每个点的密度来实现。例如:

# Simulate some data and put in data frame DF
n <- 100
x <- rnorm(n)
y <- 3 + 2* x * rexp(n) + rnorm(n)
# add some outliers
y[sample(1:n,20)] <- rnorm(20,20,20)
DF <- data.frame(x,y)

# Calculate 2d density over a grid
library(MASS)
dens <- kde2d(x,y)

# create a new data frame of that 2d density grid
# (needs checking that I haven't stuffed up the order here of z?)
gr <- data.frame(with(dens, expand.grid(x,y)), as.vector(dens$z))
names(gr) <- c("xgr", "ygr", "zgr")

# Fit a model
mod <- loess(zgr~xgr*ygr, data=gr)

# Apply the model to the original data to estimate density at that point
DF$pointdens <- predict(mod, newdata=data.frame(xgr=x, ygr=y))

# Draw plot
library(ggplot2)
ggplot(DF, aes(x=x,y=y, color=pointdens)) + geom_point()

enter image description here

或者,如果我只是改变 n 10^6 我们得到

enter image description here

关于r - 如何获得特定点的核密度估计值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201906/

相关文章:

r - 合并表: classify output according to how rows where joined

r - 具有自定义 bin 边缘的 ggplot2 密度直方图

r - 用透明颜色填充密度曲线

python - 自适应带宽核密度估计

r - 从命名空间获取管道操作符

r - 使用ggplot绘制趋势线

python - seaborn kde 图中的级别是什么意思?

python - `python` 中的加权高斯核密度估计

rbindlist : NA into date-time column

scipy gaussian_kde和循环数据