我正在尝试处理 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()
或者,如果我只是改变 n 10^6 我们得到
关于r - 如何获得特定点的核密度估计值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16201906/