是否可以将多边形剪切到基本地图的边界框?

时间:2014-02-19 14:38:52

标签: r ggmap

我有一个相邻政府区域的多边形叠加,我想在不同的地图上显示区域中的数据,但由于底图的边界框小于多边形,后者是扭曲的:

map output

我用过的代码是

#basemap bounds
minmaxx <- c(-0.48384, -0.29955)
minmaxy <- c(51.2904, 51.41771)
mymapextent <- cbind(minmaxx, minmaxy)

districtboundary<- fortify(readShapePoly("maps/districts84/districts84.shp"))
pdistrictboundary<-geom_polygon(data=districtboundary, aes(x=long, y=lat, group=group), colour= "red", fill=NA)

map1 <- ggmap(get_map(location= bbox(mymapextent),  source='osm', color='bw'))
map1 <- map1 + geom_point(data=pointstestlatlong, aes(Longitude_Decimal, Latitude_Decimal, colour=CasualtySeverity))
map1 <-  map1 + pdistrictboundary

print(map1)

有没有办法可以将多边形剪切到边界框?

1 个答案:

答案 0 :(得分:0)

根据Josh的提示,这个功能应该有效。它接受bb参数的边界框或栅格范围对象:

clip_spdf <- function(shp, bb, byid = T){
  if(class(bb)[1] == "Extent") e <- bbox(bb) else bb <- e
  e <- rgeos::readWKT(paste('POLYGON((',e[1,1],e[2,1],',',e[1,1],e[2,2],',',e[1,2],e[2,2],',',e[1,2],e[2,1],',',e[1,1],e[2,1],'))',collapse=' '))
  e@proj4string <- shp@proj4string
  rgeos::gIntersection(shp, e, byid=byid)
}