Skip to content

Instantly share code, notes, and snippets.

@hrbrmstr
Created May 14, 2015 18:51
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 hrbrmstr/4efedf3b24f7da4e24d1 to your computer and use it in GitHub Desktop.
Save hrbrmstr/4efedf3b24f7da4e24d1 to your computer and use it in GitHub Desktop.
hexbin statebins in R via GeoJSON
library(rgdal)
library(rgeos)
library(ggplot2)
# get GeoJSON from https://team.cartodb.com/u/andrew/tables/andrew.us_states_hexgrid/public/map
# Read in GeoJSON ---------------------------------------------------------
us <- readOGR("us_states_hexgrid.geojson", "OGRGeoJSON")
# Get centers of polygns for label placement ------------------------------
centers <- cbind.data.frame(data.frame(gCentroid(us, byid=TRUE), id=us@data$iso3166_2))
# Convert base shapefile into something ggplot can handle -----------------
us_map <- fortify(us, region="iso3166_2")
gg <- ggplot()
# Plot base map -----------------------------------------------------------
gg <- gg + geom_map(data=us_map, map=us_map,
aes(x=long, y=lat, map_id=id),
color="white", size=0.5)
# Plot filled polygons ----------------------------------------------------
gg <- gg + geom_map(data=us@data, map=us_map,
aes(fill=bees, map_id=iso3166_2))
# Overlay borders without ugly line on legend -----------------------------
gg <- gg + geom_map(data=us@data, map=us_map,
aes(map_id=iso3166_2),
fill="#ffffff", alpha=0, color="white",
show_guide=FALSE)
# Place state name in center ----------------------------------------------
gg <- gg + geom_text(data=centers, aes(label=id, x=x, y=y), color="white", size=4)
# ColorBrewer scale; using distiller for discrete vs continuous -----------
gg <- gg + scale_fill_distiller(palette="RdPu", na.value="#7f7f7f")
# coord_map mercator works best for the display ---------------------------
gg <- gg + coord_map()
# Remove chart junk for the “map" -----------------------------------------
gg <- gg + labs(x=NULL, y=NULL)
gg <- gg + theme_bw()
gg <- gg + theme(panel.border=element_blank())
gg <- gg + theme(panel.grid=element_blank())
gg <- gg + theme(axis.ticks=element_blank())
gg <- gg + theme(axis.text=element_blank())
gg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment