Created
November 5, 2021 14:59
-
-
Save walkerke/c0bdc1a87195ebe803ee0c796cb17021 to your computer and use it in GitHub Desktop.
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
library(mapboxapi) | |
library(tidycensus) | |
library(tidyverse) | |
library(sf) | |
library(ggspatial) | |
options(tigris_use_cache = TRUE) | |
# Get the data from the ACS | |
tarrant <- get_acs( | |
geography = "tract", | |
variables = "B25077_001", | |
state = "TX", | |
county = "Tarrant", | |
geometry = TRUE | |
) | |
# Convert to centroids and omit NAs | |
tarrant_pts <- tarrant %>% | |
st_transform(26914) %>% | |
st_centroid() %>% | |
na.omit() | |
# Make a raster template at 250m resolution | |
raster_template <- tarrant %>% | |
st_transform(26914) %>% | |
raster::raster(resolution = 250) | |
# Compute inverse distance weighted interpolation with an exponent of 2 | |
# and a nearest-neighbor cutoff of 20 | |
idw_formula <- gstat::gstat( | |
formula = estimate ~ 1, | |
locations = tarrant_pts, | |
nmax = 20, | |
set = list(idp = 2) | |
) | |
# Interpolate the IDW to the raster | |
idw_raster <- raster::interpolate(raster_template, idw_formula) | |
# Grab a custom basemap using the dev version of mapboxapi | |
# remotes::install_github("walkerke/mapboxapi") | |
base <- get_static_tiles( | |
location = idw_raster, | |
zoom = 10, | |
style_id = "ckedp72zt059t19nssixpgapb", | |
username = "kwalkertcu" | |
) | |
# Map it out with ggplot2 and ggspatial | |
ggplot() + | |
layer_spatial(base) + | |
layer_spatial(idw_raster, alpha = 0.5) + | |
scale_fill_viridis_c(labels = scales::dollar, na.value = "transparent") + | |
coord_sf(datum = NA) + | |
theme_bw(base_family = "Open Sans") + | |
scale_x_continuous(expand = c(0, 0)) + | |
scale_y_continuous(expand = c(0, 0)) + | |
labs(fill = "Median home value,\n2015-2019 ACS\n(interpolated)", | |
caption = "Basemap © Mapbox, © OpenStreetMap") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment