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

时间:2017-04-03 16:50:47

标签: r ggplot2 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

enter image description here 结果显示在图片中,有3个地方脱颖而出,但我怎样才能在这些区域的中间得到纬度和长度?(红点)

1 个答案:

答案 0 :(得分:6)

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)

enter image description here

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