How to get contour lines around the grids in R-raster?

安稳与你 提交于 2019-12-04 04:12:46

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!