问题
Having a raster in R, how can I draw a contour line around the grids (not joining the centers or anything else, really following the boundaries of the grids) having some value (or identified by some mask)?
The following example shows how to get the contour lines around areas with value 0.6: how to do the same but with the lines following the borders of the grids?
The function should return an object to add to a plot (as a SpatialLinesDataFrame
for rasterToContour
), and adjacent grids should be included in one single contour line (i.e., only the outer boundaries of a polygon should be drawn). I couldn't find the solution with rasterToPolygons
(see here for a visual aspect, but it didn't help me here).
set.seed(2)
r <- raster(nrow=10, ncol=10)
r[] <- runif(ncell(r))
r[r>0.6] <- 0.6
rc <- rasterToContour(r, levels=c(0.6))
plot(r)
plot(rc, add=TRUE)
回答1:
I'd use a combination of clump()
and rasterToPolygons()
:
library(raster)
library(rgeos) ## For dissolve = TRUE in rasterToPolygons()
## Recreate your data
set.seed(2)
r <- raster(nrow = 10, ncol = 10)
r[] <- runif(ncell(r))
plot(r)
## Compute and then plot polygons surrounding cells with values greater than 0.6
SP <- rasterToPolygons(clump(r > 0.6), dissolve = TRUE)
plot(SP, add = TRUE)
来源:https://stackoverflow.com/questions/28859181/how-to-get-contour-lines-around-the-grids-in-r-raster