Overlaying polygons on ggplot map

I'm struggling to overlay neighborhood boundaries on a google map. I'm trying to follow this code. My version is below. Do you see anything obviously wrong?

#I set the working directory just before this...
chicago = readOGR(dsn=".", layer="CommAreas")
overlay <- spTransform(chicago,CRS("+proj=longlat +datum=WGS84"))
overlay <- fortify(overlay)
location <- unlist(geocode('4135 S Morgan St, Chicago, IL 60609'))+c(0,.02)
ggmap(get_map(location=location,zoom = 10, maptype = "terrain", source = "google",col="bw")) +
  geom_polygon(aes(x=long, y=lat, group=group), data=overlay, alpha=0)+
  geom_path(color="red")

Any insight would be much appreciated. Thanks for your help and patience.

Upvotes: 2

Views: 8833

Answers (1)

hrbrmstr
hrbrmstr

Reputation: 78832

This worked for me:

library(rgdal)
library(ggmap)

# download shapefile from:
#   https://data.cityofchicago.org/api/geospatial/cauq-8yn6?method=export&format=Shapefile

# setwd accordingly

overlay <- readOGR(".", "CommAreas")
overlay <- spTransform(overlay, CRS("+proj=longlat +datum=WGS84"))
overlay <- fortify(overlay, region="COMMUNITY") # it works w/o this, but I figure you eventually want community names

location <- unlist(geocode('4135 S Morgan St, Chicago, IL 60609'))+c(0,.02)

gmap <- get_map(location=location, zoom = 10, maptype = "terrain", source = "google", col="bw")

gg <- ggmap(gmap)
gg <- gg + geom_polygon(data=overlay, aes(x=long, y=lat, group=group), color="red", alpha=0)
gg <- gg + coord_map()
gg <- gg + theme_bw()
gg

enter image description here

You might want to restart your R session in the event there's anything in the environment causing issues, but you can set the line color and alpha 0 fill in the geom_polygon call (like I did).

You can also do:

gg <- gg + geom_map(map=overlay, data=overlay, 
                    aes(map_id=id, x=long, y=lat, group=group), color="red", alpha=0)

instead of the geom_polygon which gives you the ability to draw a map and perform aesthetic mappings in one call vs two (if you're coloring based on other values).

Upvotes: 7

Related Questions