0

The objective is to create heatmap polygons from a points shapefile named "df_sf" for an attribute "V1" in the shapefile and then export these polygons as another shapefile in R.

What I have tried?

  1. I have implemented the script here to generate density plots for the points using Lat and Long data not the variable "V1" value: Create density polygons from spatial points in R

  2. tmaps cannot be exported as shapefile and the code below does not create polygons

p1 <- st_read("spatialdata.shp")

df_sf <- sf::st_as_sf(p1)

# Install and load required packages
install.packages(c("sf", "dplyr", "tmap", "sfheaders"))
library(sf)
library(dplyr)
library(tmap)
library(sfheaders)

# Create heatmap polygons
heatmap_polygons <- df_sf %>%
  st_transform(st_crs(4326)) %>%
  tm_shape() +
  tm_dots(col = "V1", palette = "Reds", size = 0.1, alpha = 0.5) +
  tm_layout()

tm_view(legend.position = c("right", "bottom"))

tmap_leaflet(heatmap_polygons)

st_write(heatmap_sf, "heatmap_polygons.shp")

Error: Error in UseMethod("st_write") : 
  no applicable method for 'st_write' applied to an object of class "tmap"

1 Answer 1

0

More correct nomenclature is that you want to calculate the kernel density of your points then create a polygon based on a contour of the resulting density. An easy way to think contour in this regard is using the percent volume (eg., what data is contained within the 60% volume of the data). This is common in deriving resource selection in species movement (telemetry) models. Here is a quick worked example.

Add libraries and create example data

library(sf)
library(spatialEco)
library(terra)

e <- rast(system.file("extdata/elev.tif", package="spatialEco"))
poly <- bbox_poly(e) 
p <- st_sf(st_sample(poly, size=100))

Now, we calculate the density of the points, calculate the percent volume contour and coerce to polygon.

d <- sf.kde(p, res = 1000) # KDE
v <- raster.vol(d, 0.60)   # volume contour
  v[v == 0] <- NA
vpoly <- st_as_sf(as.polygons(v))

plot(d, legend=FALSE)
  plot(vpoly, add=TRUE, col=NA)
  plot(p, pch=20, add=TRUE)

density and polygon

3
  • Error in h(simpleError(msg, call)) : error in evaluating the argument 'x' in selecting a method for function 'rast': unable to find an inherited method for function ‘ext’ for signature ‘"sfc_POINT"’
    – vp_050
    Commented Jan 25 at 14:31
  • This script does not answer the question. We want heatmap not density for a variable V1 in the shapefile.
    – vp_050
    Commented Jan 25 at 14:32
  • vp_050 heatmaps are a common lay term for kernel density estimates (KDE). This example is not returning a weighted KDE but, simply the 2D density of points per the bandwidth area. Although, the sf.kde allows for a weighted density. Commented Jan 25 at 21:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.