Skip to content

Instantly share code, notes, and snippets.

@Ram-N
Created March 28, 2016 00:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ram-N/8082e366ec437905bae5 to your computer and use it in GitHub Desktop.
Save Ram-N/8082e366ec437905bae5 to your computer and use it in GitHub Desktop.
Deconstructing Hexbix US map plot
#understanding the code behind Bob Rudis' blog post
#https://rud.is/b/2015/05/14/geojson-hexagonal-statebins-in-r/
rm(list=ls())
library(rgdal)
library(rgeos)
require(maptools)
setwd("~/RStats/data")
ogrInfo("us_states_hexgrid.geojson", "OGRGeoJSON")
ushexjson <- readOGR("us_states_hexgrid.geojson", "OGRGeoJSON")
plot(ushex)
jj
us_hex_map <- fortify(ushex, region='iso3166_2')
names(us_hex_map)
ushex
ushex@data
mp <- ggplot(data=us_hex_map, aes(map_id=id, x=long, y=lat)) +
# Plot base map ----------------------------------------------
geom_map(map=us_hex_map, #map has lat and long, grouped by id
color="black",
fill="white")
gg <- ggplot()
# Plot base map -----------------------------------------------------------
gg <- gg + geom_map(data=us_hex_map, map=us_hex_map,
aes(x=long, y=lat, map_id=id),
color="white", size=0.5)
gg
# Plot filled polygons ----------------------------------------------------
gg <- gg + geom_map(data=ushexjson@data, map=us_hex_map,
aes(fill=bees, map_id=iso3166_2))
gg
# Remove chart junk
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
gg <- gg + geom_map(data=ushexjson@data, map=us_hex_map,
aes(map_id=iso3166_2),
fill="#ffffff", alpha=0, color="white",
show_guide=FALSE)
gg
gg <- gg + scale_fill_distiller(palette="RdPu", na.value="#7f7f7f")
gg
gg <- gg + coord_map()
#Let's add in the centers
centers <- cbind.data.frame(data.frame(
gCentroid(ushexjson, byid=TRUE), #in rGeos pkg byID gives a center for each ID region
id=ushexjson@data$iso3166_2))
gg <- gg + geom_text(data=centers, aes(label=id, x=x, y=y), color="white", size=3)
gg
#gCentroid(ushexjson), byid=TRUE)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment