[GIS] ggmap: clip a map

ggmapggplot2maptoolsr

I'm using ggmap to grab Washington DC and I have a shapefile that I downloaded from here:

library(ggplot2)
library(ggmap)
library(maptools)

dc = get_map(location = 'DC', zoom = 12)

nhbds = readShapePoly("Census_Tracts_-_2010.shp")

ggmap(dc) + 
  geom_polygon(aes(x = long, y = lat, group = group), 
           data = nhbds,
           alpha = 0.8, 
           color = "black",
           size = 0.2)

Here's the plot

I'd like to clip the map to the borders of the city only, getting rid of Virginia and Maryland. And I don't actually want to overlay the tracts.

Any simple ways to do this? Here's a nice map that looks like what ultimately I want to accomplish:

DC map

Best Answer

Robin Lovelace has provided a nice little function to download a ggmap object and convert it to a raster. Using this you could do:

library(ggmap)
library(raster)
library(rgdal)

# courtesy R Lovelace
ggmap_rast <- function(map){
  map_bbox <- attr(map, 'bb') 
  .extent <- extent(as.numeric(map_bbox[c(2,4,1,3)]))
  my_map <- raster(.extent, nrow= nrow(map), ncol = ncol(map))
  rgb_cols <- setNames(as.data.frame(t(col2rgb(map))), c('red','green','blue'))
  red <- my_map
  values(red) <- rgb_cols[['red']]
  green <- my_map
  values(green) <- rgb_cols[['green']]
  blue <- my_map
  values(blue) <- rgb_cols[['blue']]
  stack(red,green,blue)
}

dc <- get_map(location = 'DC', zoom = 12) 
dc.rast <- ggmap_rast(map = dc) # convert google map to raster object
nhbds <- readOGR("Census_Tracts_-_2010", "Census_Tracts_-_2010") # use rgdal to preserve projection
dc.only <- mask(dc.rast, nhbds) # clip to bounds of census tracts

# prep raster as a data frame for printing with ggplot
dc.df <- data.frame(rasterToPoints(dc.only))
ggplot(dc.df) + 
  geom_point(aes(x=x, y=y, col=rgb(layer.1/255, layer.2/255, layer.3/255))) + 
  scale_color_identity()

enter image description here

Related Question