SpatialKDE implements kernel density estimation for spatial data with all the necessary settings, including selection of bandwidth, kernel type and underlying grid (cell size and shape). The algorithm is based on Heatmap tool from QGIS. The tool is adapted directly from source code. Example tutorial about the QGIS tool is available here.
First we load all necessary packages.
Then we load the example dataset and prepare it into expected format
of sf
data.frame
.
data(meuse)
meuse <- meuse %>%
st_as_sf(coords = c("x", "y"), dim = "XY") %>%
st_set_crs(28992) %>%
select()
Let’s define variables necessary for KDE estimation, cell size of the resulting grid and band width of points.
Now we can prepare grid for KDE estimation. We prepare rectangular grid (hexagonal is the second option) with given cell size which is slightly bigger than convex hull of the data.
At this moment it is possible to calculate KDE using
kde()
function with specified settings.
## Using centroids instead of provided `grid` geometries to calculate KDE estimates.
The result can be visualized using tmap
package.
tm_shape(kde) +
tm_polygons(col = "kde_value", palette = "viridis", title = "KDE Estimate") +
tm_shape(meuse) +
tm_bubbles(size = 0.1, col = "red")
##
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_tm_polygons()`: migrate the argument(s) related to the scale of
## the visual variable `fill` namely 'palette' (rename to 'values') to fill.scale
## = tm_scale(<HERE>).
## [v3->v4] `tm_polygons()`: use 'fill' for the fill color of polygons/symbols
## (instead of 'col'), and 'col' for the outlines (instead of 'border.col').
## [v3->v4] `tm_polygons()`: migrate the argument(s) related to the legend of the
## visual variable `fill` namely 'title' to 'fill.legend = tm_legend(<HERE>)'
Now we can prepare raster for KDE estimation. We prepare raster with given cell size which is slightly bigger than convex hull of the data.
At this moment it is possible to calculate KDE using
kde()
function with specified settings.
The result can be visualized using tmap
package.
tm_shape(kde) +
tm_raster(palette = "viridis", title = "KDE Estimate") +
tm_shape(meuse) +
tm_bubbles(size = 0.1, col = "red") +
tm_layout(legend.outside = TRUE)
##
## ── tmap v3 code detected ───────────────────────────────────────────────────────
## [v3->v4] `tm_tm_raster()`: migrate the argument(s) related to the scale of the
## visual variable `col` namely 'palette' (rename to 'values') to col.scale =
## tm_scale(<HERE>).
## [v3->v4] `tm_raster()`: migrate the argument(s) related to the legend of the
## visual variable `col` namely 'title' to 'col.legend = tm_legend(<HERE>)'