在 R 中的二维直方图中查找高密度区域

Finding high density zones in a 2D Histogram in R

我使用 MASS 的 kde2d 函数按以下方式创建了一系列二维直​​方图:

    # Loading libraries
    library(MASS)
    library(RcolorBrewer)
    # Loading data
    data <- as.matrix(read.table('data.dat'))
    # Create the 2dhist object      
    hist_2d <- kde2d(data[,1],data[,2],n = 60, lims=c(-180,180,-180,180))
    # Define the color palette
    rf <- colorRampPalette(rev(brewer.pal(11,'Spectral')))
    r <- rf(60)
    # Defining the axis
    at_x = seq(-180,180,by=30)
    at_y = seq(-180,180,by=30)
    # Plot the 2DHistogram
    image(hist_2d,col=r,cex.main=3,main='Q68L',axes=F)
    axis(1,lwd.ticks=2,at=at_x,labels=T,cex.axis=2)
    axis(2,lwd.ticks=2,at=at_y,labels=T,cex.axis=2)

生成直方图looks like this. How I can identify all the zones with high density ( which I marked inside the white squares)?这个问题的理想解决方案是一个函数,它为每个高密度区域抛出一个 (x,y) 范围,以便它可以应用于多个数据集。

在此先致谢,如果您需要更多信息,请告诉我

通过正确的数据表示,这可以通过 聚类分析。由于您不提供数据,我将说明 使用 kde2d 帮助页面上使用的数据 - 间歇泉数据。 此数据非常清楚地分离了 "high density" 区域(如您的示例图片),所以我将只使用一个简单的 k 均值聚类。

library(MASS)
attach(geyser)
f2 <- kde2d(duration, waiting, n = 50, lims = c(0.5, 6, 40, 100),
            h = c(width.SJ(duration), width.SJ(waiting)) )
image(f2, zlim = c(0, 0.05))

我们需要找到 "hot spots"。为了了解 应该考虑哪些值"high",我们可以看一个箱线图。

boxplot(as.vector(f2$z))

基于此,我会有些武断地使用点 z 值大于 0.012。你需要调整这个 你的特殊问题。

Hot = which(f2$z > 0.012, arr.ind = TRUE)
HotPoints = data.frame(x=f2$x[Hot[,1]], y=f2$y[Hot[,2]])
plot(HotPoints, pch=20, xlim = c(0.5,6), ylim = c(40,100))

现在我们需要对点进行聚类并找到 x 和 y 范围 对于集群。首先,我简单地做一下,并表明 结果是合理的。

KM3 = kmeans(scale(HotPoints), 3)
plot(HotPoints, pch=20, xlim = c(0.5,6), ylim = c(40,100))
for(i in 1:3) {
    Rx = range(HotPoints[KM3$cluster == i,1])
    Ry = range(HotPoints[KM3$cluster == i,2])
    polygon(c(Rx, rev(Rx)), rep(Ry, each=2))
}

我不确定您希望如何将结果呈现给您, 但是将它们全部放在一个地方的一种方法是:

XRanges = sapply(unique(KM3$cluster), 
    function(i) range(HotPoints[KM3$cluster == i,1]))
XRanges
         [,1]     [,2]     [,3]
[1,] 3.979592 3.867347 1.734694
[2,] 4.877551 4.316327 2.071429
YRanges = sapply(unique(KM3$cluster), 
    function(i) range(HotPoints[KM3$cluster == i,2]))
YRanges
         [,1]     [,2]     [,3]
[1,] 47.34694 70.61224 73.06122
[2,] 62.04082 87.75510 95.10204

这给出了三个聚类中每个聚类的 x 和 y 的最小值和最大值。

但是,我在这里做了一些选择,我想指出 我还给你留了一些工作。 还需要做什么:
1.密度多高需要选择分界点 需要得到一个集群。
2. 鉴于高于你的截止点,你需要说 你想生成多少个集群。

其余的机器都在那里。