Skip to content

Instantly share code, notes, and snippets.

@walkerke
Last active November 8, 2021 17:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save walkerke/9eefc69d87b2b8264e73dec41a66b669 to your computer and use it in GitHub Desktop.
Save walkerke/9eefc69d87b2b8264e73dec41a66b669 to your computer and use it in GitHub Desktop.
library(mapboxapi)
library(tidycensus)
library(tidyverse)
library(tmap)
library(ggspatial)
options(tigris_use_cache = TRUE)
# Get the data from the ACS
#
# Requires a Census API key: read https://walker-data.com/census-r/an-introduction-to-tidycensus.html#getting-started-with-tidycensus
# for tips on getting started with tidycensus
#
tarrant <- get_acs(
geography = "tract",
variables = "B25077_001",
state = "TX",
county = "Tarrant",
geometry = TRUE
)
# get_static_tiles() is in the brand-new version of mapboxapi;
# Update to version 0.3 from CRAN with install.packages("mapboxapi") or
# install from GitHub with remotes::install_github("walkerke/mapboxapi")
# My custom style ID and username; won't work without my token
# Your token can be set with the `mb_access_token()` function
# Then, grab your style ID and username from Mapbox Studio
#
# How to find your style ID: https://docs.mapbox.com/help/glossary/style-url/
#
basemap <- get_static_tiles(
location = tarrant,
zoom = 10,
style_id = "ckedp72zt059t19nssixpgapb",
username = "kwalkertcu"
)
# Use this instead if you don't have a style of your own to use yet
#
# Available Mapbox style IDs are here: https://docs.mapbox.com/api/maps/styles/#mapbox-styles
#
# basemap <- get_static_tiles(
# location = tarrant,
# zoom = 10,
# style_id = "light-v9",
# username = "mapbox"
# )
# Uses the "Roboto" Google font below; change if you don't have it or install it
# sysfonts::font_add_google("Roboto", "Roboto")
# tmap:
tm_shape(basemap) +
tm_rgb() +
tm_shape(tarrant) +
tm_polygons(col = "estimate",
alpha = 0.5, palette = "cividis",
title = "Median home value\n2015-2019 ACS") +
tm_layout(legend.outside = TRUE, fontfamily = "Roboto") +
tm_credits("Basemap © Mapbox, © OpenStreetMap", position = c("RIGHT", "BOTTOM"))
# ggplot2:
ggplot() +
layer_spatial(data = basemap) +
theme_bw(base_family = "Roboto") +
geom_sf(data = tarrant, aes(fill = estimate), alpha = 0.5, lwd = 0.2) +
coord_sf(datum = NA) +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0)) +
scale_fill_viridis_c(option = "cividis", labels = scales::dollar) +
labs(fill = "Median home value\n2015-2019 ACS",
caption = "Basemap © Mapbox, © OpenStreetMap")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment