Sunday, 27 May 2018

raster - How can I generate a fishnet grid and a matrix of percentage of overlapping in R?


I'm trying use R for create a fishnet grid like in arcGIS with many cells of same size.


In the arcGIS 9.3 we have the option of create a polygon with many small square polygons (eg. 1 x 1 degree of lat and long) in the extent of our study area using the tool 'create fishnet' (http://webhelp.esri.com/arcgisdesktop/9.3/index.cfm?TopicName=Create_Fishnet_(Data_Management)) and after aply the tool 'Feature to Polygon' to transform the polygon lines in square polygons. Other option is use the “Hawth’s Tools” extension and acess the “Sampling Tools” -> “Create Vector Grid (line/polygon) but the extension only work properly until arcGIS 9.2.


Then I want create the fishnet grid (polygon with many regular squares) and after calculate many percentage of overlap of some polygons to each cell of the fishnet and create a matrix with each cell in lines and each polygon in the columns, like this matrix.



Answer




I found a really simple and good solution with the rasterize function from raster package



library(raster)
library(sp)



Create polygons



x_coord <- c(0,  1,  6, 4, 2)
y_coord <- c(10, 5, 5, 12, 10)
xym <- cbind(x_coord, y_coord)
p1 = Polygon(xym)
p2 = Polygon(xym - 3)
ps1 = Polygons(list(p1), 1)

ps2 = Polygons(list(p2), 2)
sps = SpatialPolygons(list(ps1, ps2))
proj4string(sps) = CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")


Create a SpatialPolygonsDataFrame



spdf = SpatialPolygonsDataFrame(sps, data.frame(col1 = 1:2))



Create a raster of the study area



fishnet.r <- raster(extent(spdf)+5)
res(fishnet.r) <- 2
proj4string(fishnet.r) <- CRS("+proj=longlat +datum=WGS84 +no_defs +ellps=WGS84 +towgs84=0,0,0")


check the inputs



fishnet <- rasterToPolygons(fishnet.r)

plot(fishnet)
plot(spdf, col = 1:2, add = T)

enter image description here



Get the percentage cover of polygons for all cells



l <- vector('list', length(spdf))
for(i in 1:length(spdf)) {
l[[i]] <- rasterize(spdf[i, ], fishnet.r, getCover = TRUE)

}
b <- brick(l)
plot(b)

enter image description here



Get the percentage in matrix format



m.out <- as.matrix(b)



Transform from RasterBrick to polygon (fishnet)



fishnet.out <- rasterToPolygons(b)

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...