Skip to content

Instantly share code, notes, and snippets.

@awhstin
Last active March 1, 2017 15:31
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 awhstin/d6a9f668a73f0b6f4d9b06672e70aac2 to your computer and use it in GitHub Desktop.
Save awhstin/d6a9f668a73f0b6f4d9b06672e70aac2 to your computer and use it in GitHub Desktop.
library(acs)
library(ggplot2)
library(plyr)
library(tidyr)
library(maps)
library(viridis)
library(hrbrthemes)
#key
api.key.install(key="pasteyourkeyhere")
# load the boundary data for all counties
county.df<-map_data("county")
# rename fields for later merge
names(county.df)[5:6]<-c("state","county")
state.df<-map_data("county")
us.county<-geo.make(state="*", county="*")
# .. and a single command to fetch the data...!
us.raw<-acs.fetch(endyear=2015,geography=us.county, table.number="B19001", col.names="pretty")
tests<-data.frame(us.raw@acs.colnames)
strings<-strsplit(as.character(tests$us.raw.acs.colnames),":")
col.names<-sapply(strings,"[",2)
income.brackets<-data.frame(county=geography(us.raw)[[1]], us.transport=as.numeric(estimate(us.raw)),
paste0(str_pad(us.raw@geography$state, 2, "left", pad="0"),
str_pad(us.raw@geography$county, 3, "left", pad="0"),
str_pad(us.raw@geography$tract, 6, "left", pad="0")),
us.raw@estimate, stringsAsFactors = FALSE)
names(income.brackets)[4:20]<-col.names
names(income.brackets)[3]<-'zip'
income.brackets[5:20] <- 100*(income.brackets[5:20]/income.brackets[,4])
#small & tidy frame
new<-income.brackets%>%gather(key=level,value=rate,4:20)
new$level<-trimws(new$level)
new<-subset(new,level == '$200,000 or more')
# clean up county names and find the states, the parish bits are for Louisiana
new$state<-tolower(gsub("^.*County, |^.*Parish, ", "", new$county))
new$county<-tolower(gsub(" County,.*| Parish,.*", "", new$county))
choropleth<-merge(county.df, new, by=c("state","county"))
choropleth<-choropleth[order(choropleth$order), ]
ggplot(choropleth, aes(long, lat, group = group)) +
geom_polygon(aes(fill = rate), colour = alpha("gray", 1 / 2), size = 0.2) +
geom_polygon(data = state.df, colour = "white", fill = NA,cex=.25) +
scale_fill_viridis(option="magma",direction = -1)+
theme(legend.position = 'bottom')+
labs(title='Income level by county',subtitle='Percent of total households with an income greater or equal to $200,000',caption="Data: American Community Survey\nU.S. Census Bureau")+
theme_ipsum()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment