Skip to content

Instantly share code, notes, and snippets.

@davidbody
Created March 7, 2017 15:54
Show Gist options
  • Save davidbody/e2b0912358e58ada7a274691272ed3d2 to your computer and use it in GitHub Desktop.
Save davidbody/e2b0912358e58ada7a274691272ed3d2 to your computer and use it in GitHub Desktop.
Iowa precinct shapefile example
library(rgdal)
library(broom)
library(ggplot2)
setwd("~/work/data/iowa-election-results/")
# Download the shapefile data if we don't already have it
if (!file.exists("./data")) {
dir.create("./data")
if (!file.exists("./data/pcts_04172014_0908am.zip")) {
dataUrl <- "https://sos.iowa.gov/shapefiles/Statewide%20Precinct%20Layer/pcts_04172014_0908am.zip"
download.file(dataUrl, destfile="./data/pcts_04172014_0908am.zip", method="libcurl")
library(utils)
unzip("./data/pcts_04172014_0908am.zip", exdir="./data")
}
}
# Read the shapefile
precincts <- readOGR(dsn="data/pcts_04172014_0908am", layer="Precincts041714")
# Extract a subset, for example Senate District 10
s10_precincts <- subset(precincts, Senate_Dis == '10')
# Plot the precincts
precincts_df <- tidy(s10_precincts)
p <- ggplot(precincts_df) + aes(long, lat, group=group)
p <- p + geom_polygon(fill="purple") + geom_path(color="white") + coord_equal()
p <- p + ggtitle("Iowa Senate District 10")
p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment