The terra::extract
function samples raster data from the top to the bottom and from left to right. This creates an issue if you're using a line to sample a raster with plan of plotting the data as a cross section. And I think the issue only occurs if the line is sloping top-right to bottom-left. And the issue is more pronounced the lower the slope of the line.
Below is a reproducible example of the problem. Any suggestions on fixes? I believe the raster
package as well as the exactextractr
packages have similar problems so maybe there isn't a clean solution except to run a smoothing filter over the sample.
# Load packages
library(terra)
# Create a sample raster
r <- rast(nrow=10, ncol=10)
r[] <- 1:ncell(r)
# Create a line geometry
l <- st_linestring(matrix(c(-150, 150, -20, 20), ncol=2))
l <- vect(l)
# Extract raster values along line
extract <- terra::extract(r, l,xy=TRUE)
extract$sample_order <- 1:nrow(extract)
# Plot the results
plot(r)
plot(l,add=TRUE)
text(extract$x, extract$y, labels=extract$sample_order, cex=0.8,add=TRUE)