Load Libraries

This is a similar walk-through for creating a map using data from the American Community Survey.

If you’re joining tables I would recommend creating a map with a single table first because it’s very easy to mess up the map alignment when you add tables.

library(tidyverse)
library(tidycensus)
library(lubridate)
library(leaflet)
library(stringr)
library(sf)

Load Census Data

*An API key will be needed to access Census data.

The following code chunks are used to pull the data from the Census. I hid the results because the output was too long.

meck_value <- get_acs(geography = “tract”,
variables = “B25077_001”,
state = “NC”,
county = “Mecklenburg County”,
year = 2019, geometry = TRUE)

meck_median_family_income <- get_acs(geography = “tract”,
variables = “B19126_001”,
state = “NC”,
county = “Mecklenburg County”,
year = 2019,
geometry = TRUE)

Clean Data and Join Tables

Renaming columns is optional but I think it makes it easier to understand.

meck_value_rename <- meck_value %>%
  rename(median_home_value=estimate)

meck_median_family_income_rename <- meck_median_family_income %>%
  rename(median_family_income=estimate)

meck_median_family_income_rename_subset <- meck_median_family_income_rename %>% 
  as.data.frame() %>% 
  select(GEOID, median_family_income)

joined_table <- inner_join(meck_value_rename, meck_median_family_income_rename_subset)

Create Map Info

mypopup_joined_table <- paste0("GEOID: ", joined_table$GEOID, "<br>", 
                                    "Median Home Value: $",                                   
                                    round(joined_table$median_home_value,
                                          0), "<br>",
                                    "Median Family Income: $",
                                    joined_table$median_family_income
)

myLAT <- 35.22074449075387
myLNG <- -80.83915132078283

pal <- colorNumeric(palette = "viridis", 
                    domain = joined_table$median_home_value)

Create Map

meck_value %>%
  st_transform(crs = "+init=epsg:4326") %>%
  leaflet(width = "100%") %>%
  addProviderTiles(provider = "CartoDB.Positron") %>%
  setView(myLNG, myLAT, zoom = 9.5) %>%
  addPolygons(popup = mypopup_joined_table,
              stroke = FALSE,
              smoothFactor = 0,
              fillOpacity = 0.7,
              color = ~ pal(estimate)) %>%
  addLegend("bottomright", 
            pal = pal, 
            values = ~ estimate,
            title = "Median Home Value",
            labFormat = labelFormat(prefix = "$"),
            opacity = 1)