0

I have a a polygon overlay of some adjoining government districts, I want to show data in the districts on separate maps, but as the bounding box for the basemap is smaller than the polygon the latter is is distorted:

map output

The code I've used for this is

#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)

Is there a way I can clip the polygon to the bounding box?

Dave
  • 21
  • 1
  • 5
  • For a general solution, [see here](http://stackoverflow.com/questions/13982773/crop-for-spatialpolygonsdataframe/13986029#13986029). I don't know anything about ggplot's spatial mapping commands, but it looks like if you clip first, following the recipe in the linked answer, and then `fortify`, you should be fine. – Josh O'Brien Feb 19 '14 at 19:04
  • Thank you, I still get an error with this. For now I have clipped the boundary layer and I am going to try to figure it out by playing around with it. – Dave Feb 28 '14 at 18:46

1 Answers1

0

In line with Josh's tip above this function should work. It accepts for bb argument either a bounding box or raster extent object:

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)
}
geotheory
  • 22,624
  • 29
  • 119
  • 196