3

I am not able to resolve the problem that follows. I have some separate shapefiles files, each one representing a given species range. Some layers have multiple polygons.

I would prefer to solve this problem with R syntax, but as alternative option I could use QGIS.

After import these shapefiles and merging them, I would like to obtain a map representing the count of overlapping polygons. In other terms, my final output would be a sort of “heatmap” in which each cell has the value of the count of overlapping polygons (i.e. the sum of the species falling in a given cell).

Anyone could kind provide me the operative approach to accomplish this?

If required, I can provide the example layers that I'm using during my trials. Despite many many attempts, I have not reached any result.

  • 1
    rasterize each polygon object into a binary (0/1) presence/absence raster, and then make that into a stack and then sum the stack? – Spacedman Dec 17 '17 at 23:05
4

Either do what Spacedman suggests (rasterize and sum) or work directly on the polygons:

library(raster)
sp1 <- spPolygons(rbind(c(-180,-20), c(-140,55), c(10, 0), c(-140,-60), c(-180,-20)), attr=data.frame(sp=1))
sp2 <- spPolygons(rbind(c(-10,0), c(140,60), c(160,0), c(140,-55), c(-10,0)), attr=data.frame(sp=2))
sp3 <- spPolygons(rbind(c(-125,-20), c(-125,20), c(0,60), c(40,5), c(15,-45), c(-125,-20)), attr=data.frame(sp=3))

x <- list(sp1, sp2, sp3)

This gives an rgeos error (TopologyException) on the example data, but might work on your data:

#y <- do.call(bind, x)
#u <- union(y)

Alternatively:

u <- x[[1]]
for (i in 2:length(x)) {
    u <- union(u, x[[i]])
}

Now sum the numer of species:

u$nspp <- rowSums(data.frame(u), na.rm=TRUE)

And plot

spplot(u, 'nspp')

If you want a raster

r <- raster()
r <- rasterize(u, r, 'nspp')
plot(r)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.