如何在特定点获得核密度估计值?

Rya*_*son 13 r kernel-density

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

Pet*_*lis 5

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

# 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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

在此输入图像描述


Rya*_*son 5

我最终找到了我正在寻找的精确功能:interp.surfacefields包中。从帮助文本中:

使用双线性权重将矩形网格上的值插值到任意位置或另一个网格。

  • 我知道这已经很旧了......但是 `fields::interp.surface` 对你有用吗?对于上面的玩具示例,它对我不起作用,因为“newdata”和“interp.surface”输出之间的尺寸不匹配。请参阅http://stackoverflow.com/questions/43896337/use-fieldsinterp-surface-to-interpolate-from-grid-to-irregular-points。 (2认同)