Last active
December 26, 2015 04:49
-
-
Save chelsimoy/7095878 to your computer and use it in GitHub Desktop.
Creating bar chart (for sorting purposes) and, finally, a choropleth map
This file contains 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
data <- read.csv("county-data.csv") | |
#adds a county column by splitting in front of the parenthesis | |
data$county <- sapply(strsplit(as.character(data$ACCOMACK.VA.), split="\\("), function(x) { x[1] }) | |
#adds a state column by splitting after the parenthesis | |
data$state <- sapply(strsplit(as.character(data$ACCOMACK.VA.), split="\\("), function(x) { x[2] }) | |
#resplit the state data to get rid of the parenthesis sign at the end | |
data$state <- sapply(strsplit(as.character(data$state), split="\\)"), function(x) { x[1] }) | |
#getting data for each state | |
get_state_data <- function(mystate) {this_state_data <- subset(data, state == mystate) } | |
#turn data$guns into a number | |
data$guns <- as.numeric(gsub("\\,","", data$X1)) | |
#create a new dataframe that aggregates the guns for each state | |
guns_state <- aggregate(data$guns, list(data$state), sum) | |
#sort it by the number of guns so it makes a pretty graph | |
guns_state2 <- guns_state[order(guns_state$x, decreasing = TRUE), ] | |
#plot it like a boss | |
barcolors <- ifelse(guns_state2$Group.1 == "IL", "red", "lightgray") | |
barplot(guns_state2$x, ylab="Number of Guns", xlab="States", col=barcolors, border=F) | |
#add some labels | |
text(guns_state2$x + 400, guns_state2$Group.1, adj=c(.5, NA), labels=guns_state2$Group.1, col="blue", cex=.7) | |
install.packages("maptools") | |
library(maptools) | |
shapes <- readShapePoly("nytlayout_state/nytlayout_state.shp") | |
install.packages("RColorBrewer") | |
library(RColorBrewer) | |
map_data <- data.frame(shapes) | |
#getting rid of Guam and Hawaii | |
guns_state5 <- guns_state2[-53,] | |
guns_state5 <- guns_state3[-49,] | |
#match the data (make sure you put the map data first--but I don't know why) | |
match_order <- match(map_data$STATE_ABBR, guns_state5$Group.1) | |
map_data$guns <- guns_state3$x[match_order] | |
#plotting | |
map_breaks <- c(0, 50, 100, 250, 500, 750, 1000, 2500, 5000, 25000) | |
buckets <- cut(map_data$guns, breaks=map_breaks) | |
numeric_buckets <- as.numeric(buckets) | |
colors <- brewer.pal(9, "YlOrRd") | |
plot(shapes, col=colors[numeric_buckets]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment