Этот ответ основан на Как получить контурные линии вокруг сеток в R-растре? .
library(data.table)
library(raster)
Также обратите внимание, что clump
требует, чтобы пакет igraph
былустановлен, и dissolve = TRUE
в rasterToPolygons
требуется rgeos
.
# convert data.frame to data.table
# not strictly necessary, but enables use of convenient functions: dcast and rbindlist.
setDT(d)
# reshape to wide
d2 <- dcast(d, y ~ x, value.var = "sig")
# reverse order of rows to match raster order
# remove first column
# convert to matrix and then to raster
r <- raster(as.matrix(d2[ , .SD[.N:1, -1]]),
xmn = 0, xmx = ncol(d2) - 1, ymn = 0, ymx = ncol(d2) - 1)
# detect clumps of connected cells of the value TRUE
# convert raster to polygons
# dissolve polygons into multi-polygons
polys <- rasterToPolygons(clump(r), dissolve = TRUE)
# grab coordinates of individual polygons and convert to a data.table
# use idcol = TRUE to enable grouping of paths when plotting
d_poly <- rbindlist(lapply(polys@polygons,
function(x) as.data.table(x@Polygons[[1]]@coords)),
idcol = TRUE)
# plot an outline around each 'patch of significant values' using geom_path
ggplot(d, aes(x = x, y = y)) +
geom_tile(aes(fill = z)) +
geom_path(data = d_poly, aes(x = x + 0.5, y = y + 0.5, group = .id),
size = 2, color = "red")
![enter image description here](https://i.stack.imgur.com/LW4Es.png)
Данные:
d <- structure(list(x = c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L,
3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L),
y = c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L,
1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L),
sig = c(FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE, TRUE,
TRUE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, TRUE),
z = c(0.96, 0.76, 0.14, 0.93, 0.39, 0.06, 0.99, 0.77,
0.7, 0.72, 0.08, 0.94, 0.98, 0.83, 0.12, 0.42)),
row.names = c(NA, -16L), class = "data.frame")