Skip to content

Instantly share code, notes, and snippets.

@zross
Last active August 29, 2015 14:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zross/41ba249eb3c086c85813 to your computer and use it in GitHub Desktop.
Save zross/41ba249eb3c086c85813 to your computer and use it in GitHub Desktop.
ggplot2 map using borders()
# In response to a question on our ggplot2/mapping post
# (http://zevross.com/blog/2014/07/16/mapping-in-r-using-the-ggplot2-package/)
# this is an example of using ggplot2's built-in
# borders() function and an external shapefile
# The shapefile used in that blog post is a projected shapefile
# but by default the borders() function uses unprojected
# boundaries so you will need to "unproject" the shapefile
# for the borders to match. An alternative would be to assign
# a projection with map() arguments
# The shapefile is from:
# http://www.nyc.gov/html/dcp/html/bytes/districts_download_metadata.shtml
library(rgdal)
# this is projected and won't match up
# with ggplot2's default "border" layer
cnty<-readOGR("nybb.shp", layer="nybb")
proj4string(cnty) # see projection
# "unproject" this -- assign unprojected geographic coord system
# wgs84 would be nearly equivalent but we use nad83
cnty<-spTransform(cnty, CRS("+proj=longlat +datum=NAD83"))
# now it matches
library(ggplot2)
library(maps)
data(us.cities)
capitals <- subset(us.cities, capital == 2 & country.etc=="NY")
ggplot(capitals, aes(long, lat)) +
borders('state', region = c('new york')) +
geom_point(aes(size = pop)) +
geom_polygon(data=cnty, aes(long,lat, group=group))
@yuying273
Copy link

Hi,

Could you tell me how to find "mybb.shp"? When I tried cnty<-readOGR("nybb.shp", layer="nybb"), it returned with error "Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, : Cannot open file".

I am trying to get polygon map plots of the five boroughs of NYC separately, Do you know whether there is a way to do that?

Thank you very much!

Best,

Yuying
syysea@gmail.com

@yuying273
Copy link

Hi,

I got it. It turned out that I need to download "nybb.shp" before use it. Thank you very much!!

Best,

Yuying
syysea@gmail.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment