Skip to content

Instantly share code, notes, and snippets.

@chris-prener
Last active February 12, 2019 16:24
Show Gist options
  • Save chris-prener/2706df78f7835bcd2bb9298f5a9aecfd to your computer and use it in GitHub Desktop.
Save chris-prener/2706df78f7835bcd2bb9298f5a9aecfd to your computer and use it in GitHub Desktop.
Script for Creating Leaflet Map of Population Density in St. Louis
# dependencies
library(dplyr) # data wrangling
library(classInt) # calculate breaks
library(leaflet) # leaflet maps
library(sf) # spatial data tools
library(stringr) # work with strings
# load data and re-project to WGS 1984
st_read("STL_DEMOS_Nhoods.shp", stringsAsFactors = FALSE) %>%
st_transform(crs = 4326) -> popChange
# calculate population density
popChange <- mutate(popChange, pop17_den = pop17/(AREA/1000000))
# create breaks
cp_bins <- function(.data, var, n = 5, style = "jenks", round = 0, dig = 10){
# calculate breaks
breaks <- classIntervals(.data[[var]], n = n, style = style)
categories <- cut(.data[[var]], breaks = c(breaks$brks), include.lowest = TRUE, dig.lab = dig)
# parse categories
categories <- unique(categories)
categories <- gsub("[][()]", "", categories)
categories <- gsub(",", " ", categories)
categories <- word(categories, 2)
categories <- round(as.numeric(categories), digits = round)
bins <- c(0, categories)
# return output
return(bins)
}
# calculate breaks
bins <- cp_bins(popChange, var = "pop17_den")
# create color palette
pal <- colorBin("YlGnBu", domain = popChange$pop17_den, bins = bins)
# create map
popChange %>%
leaflet() %>%
addProviderTiles(providers$CartoDB.Positron) %>%
addPolygons(
color = "#444444",
weight = 1,
opacity = 1.0,
smoothFactor = 0.5,
fillOpacity = 0.5,
fillColor = ~pal(pop17_den),
highlightOptions = highlightOptions(color = "white", weight = 2, bringToFront = TRUE),
popup = paste("<b>Name:</b> ", popChange$NHD_NAME, "<br>",
"<b>2017 Population:</b> ", round(popChange$pop17, digits = 0), "<br>",
"<b>2017 Population Density (per Km^2):</b> ",
round((popChange$pop17_den), digits = 0),"<br>",
"<b>Area (Km^2):</b> ", round(popChange$AREA/1000000, digits = 2))) %>%
addLegend(pal = pal, values = ~pop17_den, opacity = .5, title = "Population Density (2017)")
# data for this example can be found here - https://github.com/slu-soc5650/lecture-05/tree/master/data/example-data/STL_DEMOS_Nhoods
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment