How do I generate the correct volume contour from a raster using sf, spatialEco, and terra?

64 Views Asked by At

I am interested in using R packages spatialEco and terra to generate some kernel density estimates with data of varying weights so that I can export contour shapefiles for mapping. I'm currently having trouble with generating a contour polygon from the data. sf.kde and raster.vol return SpatRaster objects, which I am attempting to convert to polygons via as.contour from terra. However, the resulting contours have 10 levels even though I specified the percentage I am interested in from raster.vol.

I'm not seeing any way to return a single layer from the as.contour function. Which of these levels in the spatVector returned by as.contour aligns with the percent threshold designated for the raster volume? Is there a different way to go about generating this contour?

Here is an example

# Generate 75% PVC from point data
library(sf)
library(spatialEco)
library(terra)

set.seed(500)

# Example Data
lims <- data.frame(x = c(0,10),
                   y = c(5,15))

dat <- data.frame(x = rnorm(50,  4, 1.0),
                  y = rnorm(50, 11, 0.5))

# plot(dat, xlim = lims$x, ylim = lims$y)

# Convert data to sf coordinates
dat_sf <- st_as_sf(dat, coords = c("x","y"))
# plot(dat_sf)

# Generate kde using spatialEco
dat_kde <- sf.kde(dat_sf,
                  y = NULL,
                  bw = 2,
                  res = .5,
                  ref = c(lims$x, lims$y))
# plot(dat_kde)

# Generate Percent Volume Raster from KDE
dat_vol <- raster.vol(dat_kde,
                      p = .75)

plot(dat_vol, xlim = c(2,6), ylim = c(9,13))
contour(dat_vol, add = T)

# Get Percent Volume Contour from Raster
dat_con <- as.contour(dat_vol)


Here are the resulting contours

0

There are 0 best solutions below