Skip to content

Instantly share code, notes, and snippets.

@keberwein
Last active February 23, 2023 01:34
Show Gist options
  • Save keberwein/05f633a2be293b01b52bf05553d24b93 to your computer and use it in GitHub Desktop.
Save keberwein/05f633a2be293b01b52bf05553d24b93 to your computer and use it in GitHub Desktop.
A leaflet map for R built on a shape file of US counties
library(sp)
library(rgeos)
library(rgdal)
library(maptools)
library(dplyr)
library(leaflet)
library(scales)
### Begin data prep
# Grab air/water quality data from the EPA
url = "https://data.cdc.gov/api/views/cjae-szjv/rows.csv?accessType=DOWNLOAD"
dat <- read.csv(url, stringsAsFactors = FALSE)
# Colnames tolower
names(dat) <- tolower(names(dat))
dat$countyname <- tolower(dat$countyname)
# Wide data set, subset only what we need.
county_dat <- subset(dat, measureid == "296",
select = c("reportyear","countyfips","statename", "countyname", "value", "unitname")) %>%
subset(reportyear==2011, select = c("countyfips", "value"))
# Rename columns to make for a clean df merge later.
colnames(county_dat) <- c("GEOID", "airqlty")
# Have to add leading zeos to any FIPS code that's less than 5 digits long to get a good match.
# I'm cheating by using C code. sprintf will work as well.
county_dat$GEOID <- formatC(county_dat$GEOID, width = 5, format = "d", flag = "0")
### End data prep
# Download county shape file from Tiger.
# https://www.census.gov/geo/maps-data/data/cbf/cbf_counties.html
us.map <- readOGR(dsn = ".", layer = "cb_2013_us_county_20m", stringsAsFactors = FALSE)
# Remove Alaska(2), Hawaii(15), Puerto Rico (72), Guam (66), Virgin Islands (78), American Samoa (60)
# Mariana Islands (69), Micronesia (64), Marshall Islands (68), Palau (70), Minor Islands (74)
us.map <- us.map[!us.map$STATEFP %in% c("02", "15", "72", "66", "78", "60", "69",
"64", "68", "70", "74"),]
# Make sure other outling islands are removed.
us.map <- us.map[!us.map$STATEFP %in% c("81", "84", "86", "87", "89", "71", "76",
"95", "79"),]
# Merge spatial df with downloade ddata.
leafmap <- merge(us.map, county_dat, by=c("GEOID"))
# Format popup data for leaflet map.
popup_dat <- paste0("<strong>County: </strong>",
leafmap$NAME,
"<br><strong>Value: </strong>",
leafmap$airqlty)
pal <- colorQuantile("YlOrRd", NULL, n = 20)
# Render final map in leaflet.
leaflet(data = leafmap) %>% addTiles() %>%
addPolygons(fillColor = ~pal(airqlty),
fillOpacity = 0.8,
color = "#BDBDC3",
weight = 1,
popup = popup_dat)
@aliechoes
Copy link

It helped me a lot :-) Thanks

@michi0x
Copy link

michi0x commented Feb 22, 2018

Hi! Thank you for posting this.
Having a small problem and I am new to plotting data such as this. I tried to recreate this as well as use manipulate and use my own data in RStudio and it is crashing. I also got an error about the colorQuantile for "YlOrRd" exceeding the limit of n (n=9 max) before the crash. Any immediate thoughts on why it could be crashing? The dataset you use is significantly larger than mine. Thanks!

@dp1900
Copy link

dp1900 commented Aug 31, 2018

Great tutorial. One question, I need to remove other states in the lower 48, how can can I determine the STATEFP id#? Thanks in advance.

@makis23
Copy link

makis23 commented Sep 3, 2020

when I run

# Download county shape file from Tiger.
# https://www.census.gov/geo/maps-data/data/cbf/cbf_counties.html
us.map <- readOGR(dsn = ".", layer = "cb_2013_us_county_20m", stringsAsFactors = FALSE)

I get: ```
Error in ogrInfo(dsn = dsn, layer = layer, encoding = encoding, use_iconv = use_iconv, :
Cannot open layer

@yl2565
Copy link

yl2565 commented Jul 26, 2021

I have the same error with @makis23

@basuanirban
Copy link

Great tutorial!. How do I only display the US map and not show other countries in the background?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment