Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

r-raster

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)

enter image description here

like image 430
ztl Avatar asked Feb 11 '23 18:02

ztl


1 Answers

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)

enter image description here

like image 65
Josh O'Brien Avatar answered Feb 13 '23 06:02

Josh O'Brien