Created
March 5, 2017 22:50
-
-
Save trinker/063c43906bc728c74ea986be564c2b95 to your computer and use it in GitHub Desktop.
Map sparkline
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
p_load(ggplot2, fivethirtyeight, dplyr, gridExtra) | |
data("police_deaths") | |
police_deaths_count <- police_deaths %>% arrange(state, -year) %>% group_by(state, year) %>% count() | |
police_deaths_count <- police_deaths_count %>% arrange(state, -year) %>% | |
filter(year %in% c(1970:2015) & !state %in% c("AK", "HI", "US", "GU", "MP", "PR", "RR", "TR", "VI")) | |
# Create unique blank strip labels for empty facets | |
bl = sapply(1:37, function(n) paste(rep(" ",n),collapse="")) | |
police_deaths_count$state.name <- state.name[match(police_deaths_count$state, state.abb)] | |
police_deaths_count$state.name[police_deaths_count$state == "DC"] <- "Washington DC" | |
police_deaths_count$state.reorder <- factor(police_deaths_count$state.name, | |
levels = c(bl[1:10], "Maine", | |
bl[11:19], "Vermont", "New Hampshire", | |
"Washington", "Idaho", "Montana", "North Dakota", "Minnesota", "Illinois", "Wisconsin", "Michigan", "New York", "Massachusetts", "Rhode Island", | |
"Oregon", "Nevada", "Wyoming", "South Dakota", "Iowa", "Indiana", "Ohio", "Pennsylvania", "New Jersey", "Connecticut", bl[20], | |
"California", "Utah", "Colorado", "Nebraska", "Missouri", "Kentucky", "West Virginia", "Virginia", "Maryland", "Washington DC", bl[21], | |
bl[22], "Arizona", "New Mexico", "Kansas", "Arkansas", "Tennessee", "North Carolina", "South Carolina", "Delaware", bl[23:24], | |
bl[25:27], "Oklahoma", "Louisiana", "Mississippi", "Alabama", "Georgia", bl[28:29], | |
bl[30:33], "Texas", bl[34:37], "Florida")) | |
police_deaths_count2 <- police_deaths_count %>% filter(!(state=="NY" & year==2001)) | |
plot1 <- ggplot(subset(police_deaths_count2, is.na(state.name)==F), #take away 9-11 peak to see trends without it | |
aes(y = n, x = year)) + | |
geom_line() + | |
facet_wrap( ~ state.reorder, ncol = 11, drop = F, strip.position="bottom") + | |
theme_classic() + | |
theme(axis.text.x = element_blank(), | |
strip.background=element_blank(), | |
axis.line=element_blank(), | |
axis.ticks=element_blank()) + | |
ylab("Count of police deaths") + | |
xlab("Year (1970 - 2015)") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
From: http://stackoverflow.com/questions/42422669/arrange-ggplot-facets-in-the-shape-of-the-us/42423420#42423420
Tweet: https://twitter.com/datavisitor/status/836648582929330176