Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

ggmap

I have a problem about heatmap. I can visualize heatmap by ggmap and eyeball the most density place, but how can I get the exact long and lat of these spots. Here is the test code:

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 As the result show in the picture, there are 3 places stands out, but how can I get lat and long in the mid of these area?(the red points)

like image 860
VincentLin Avatar asked Sep 10 '25 17:09

VincentLin


1 Answers

The help for geom_density_2d says:

Description:

     Perform a 2D kernel density estimation using ‘kde2d’ 

The kde2d function is in the MASS package.

Read the docs for that and you'll see how to get a matrix of values from the kernel density that ggplot is plotting.

Then the problem is reduced to one of finding local maxima of a matrix:

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
like image 162
Spacedman Avatar answered Sep 13 '25 07:09

Spacedman