Created
January 2, 2021 09:48
-
-
Save michaeldorman/0b6979ba9425ad27dee37516d3f394f6 to your computer and use it in GitHub Desktop.
Rasterizing points, lines and polygons to raster with `st_rasterize`, using the default algorithms (top) and `options="ALL_TOUCHED=TRUE"` (bottom).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(stars) | |
multipoint = st_as_sfc("MULTIPOINT ((10 40), (40 30), (20 20), (30 10))")[[1]] | |
multilinestring = st_as_sfc("MULTILINESTRING ((10 10, 20 20, 10 40),(40 40, 30 30, 40 20, 30 10))")[[1]] | |
multipolygon = st_as_sfc("MULTIPOLYGON (((40 40, 20 45, 45 30, 40 40)),((20 35, 10 30, 10 10, 30 5, 45 20, 20 35),(30 20, 20 15, 20 25, 30 20)))")[[1]] | |
dat = c(st_sfc(multipoint), st_sfc(multilinestring), st_sfc(multipolygon)) | |
dat = st_sf(dat, data.frame(value = 1, type = c("Points", "Lines", "Polygons"))) | |
grid = st_as_stars(st_bbox(st_buffer(dat, 3)), dx = 3, dy = 3) | |
opar = par(mfrow = c(2, 3)) | |
for(i in 1:3) { | |
u = st_rasterize(dat[i, ], grid) | |
plot(u, col = c(NA, "lightgrey"), key.pos = NULL, main = paste0(dat$type[i], " (default)"), reset = FALSE) | |
plot(st_geometry(st_as_sf(u, as_points = TRUE)), pch = 4, col = "darkgrey", add = TRUE) | |
plot(st_geometry(dat[i, ]), add = TRUE) | |
} | |
for(i in 1:3) { | |
u = st_rasterize(dat[i, ], grid, options = "ALL_TOUCHED=TRUE") | |
plot(u, col = c(NA, "lightgrey"), key.pos = NULL, main = paste0(dat$type[i], " (ALL_TOUCHED=TRUE)"), reset = FALSE) | |
plot(st_geometry(st_as_sf(u, as_points = TRUE)), pch = 4, col = "darkgrey", add = TRUE) | |
plot(st_geometry(dat[i, ]), add = TRUE) | |
} | |
par(opar) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment