如何在ggmap中获取前N个最大密度点坐标

How to get the top-N largest density spot coordinates in ggmap

我对热图有疑问。我可以通过 ggmap 和眼球可视化热图最密度的地方,但我怎样才能得到这些点的确切长度和​​纬度。这是测试代码:

set.seed(1)
mymap <- get_map(location = "Detroit", zoom = 8)
mydata <- data.table(long = runif(min = -84, max = -82.5, n = 100),
                     lat = runif(min = 42, max = 42.7, n = 100))
g <- ggmap(mymap) +
  stat_density2d(data = mydata,
                 aes(x = long, y = lat, fill = ..level..,alpha = ..level..),
                 size = 0.5, bins = 10, geom = "polygon") + 
  scale_alpha_continuous(range(0.1,0.5))
g

结果如图所示,有3个地方突出,但是我怎么才能在这些区域的中间得到纬度和经度呢?(红点)

geom_density_2d 的帮助说:

Description:

     Perform a 2D kernel density estimation using ‘kde2d’ 

kde2d 函数在 MASS 包中。

阅读相关文档,您将了解如何从 ggplot 绘制的内核密度中获取值矩阵。

然后问题简化为寻找矩阵的局部最大值之一:

Given a 2D numeric "height map" matrix in R, how can I find all local maxima?

> library(MASS); library(raster)
> w = matrix(1,3,3)
> x = kde2d(mydata$long, mydata$lat, n=100)
> r = raster(x)
> f <- function(X) max(X, na.rm=TRUE)
> localmax <- focal(r, w, fun = f, pad=TRUE, padValue=NA)
> r2 <- r==localmax
> maxXY <- xyFromCell(r2, Which(r2==1, cells=TRUE))
> image(x,asp=1)
> points(maxXY)

> maxXY
             x        y
[1,] -82.86796 42.43167
[2,] -83.47583 42.34163
[3,] -82.83831 42.18924