I read a post about interactive maps with R using the leaflet
package.
In this article, the author created a heat map like this:
X <- cbind(lng, lat)
kde2d <- bkde2D(X, bandwidth = c(bw.ucv(X[,1]), bw.ucv(X[,2])))
x <- kde2d$x1
y <- kde2d$x2
z <- kde2d$fhat
CL <- contourLines(x , y , z)
m <- leaflet() %>%
addTiles()
m %>%
addPolygons(CL[[5]]$x, CL[[5]]$y, fillColor = "red", stroke = FALSE)
I am not familiar with the bkde2d
function, so I'm wondering if this code could be generalized to any shapefiles?
What if each node has a specific weight, that we would like to represent on the heat map?
Are there other ways to create a heat map with leaflet
map in R ?
Best Answer
Here's my approach for making a more generalized heat map in Leaflet using R. This approach uses
contourLines
, like the previously mentioned blog post, but I uselapply
to iterate over all the results and convert them to general polygons. In the previous example it's up to the user to individually plot each polygon, so I would call this "more generalized" (at least this is the generalization I wanted when I read the blog post!).Here's what you'll have at this point:![enter image description here](https://i.stack.imgur.com/PFxoj.png)
And this is what the heat map with points would look like:
Here's an area that suggests to me that I need to tune some parameters or perhaps use a different kernel: