Loading Libraries

This is a walk-through of how to create a map using data from the American Community Survey from the US Census Bureau. I will be creating a map of Mecklenburg County, NC by tract of households with children under 6 having both parents in the home and both parents in the labor force.

You’ll want to start by loading the libraries that you will be using. You can see how to do that below:

library(acs)#for accessing acs data
library(tigris)#for maps
library(leaflet)#for creating maps
library(mapview)#for saving image of map
library(stringr)#For dealing with strings
library(tidyverse)#for cleaning data

If you haven’t already, you will need to load an API key to connect to the Census database. You should only need to do this once. I will create a walkthrough for this separately but there are plenty online.

Location Codes and Shapefile

You’ll need the location codes for the area you want to create the map for. If you’re unfamiliar with them you can use this code to look them up:

lookup_code(state = "NC", county = "Mecklenburg")
## [1] "The code for North Carolina is '37' and the code for Mecklenburg County is '119'."

You’ll use those codes to create a shapefile for the map you’ll use. The code to create the shapefile is in plain text below because the output would be too long for this article.

mecklenburg_county_shapefile <- tracts(state = “37”, county = “119”)

To see how the shapefiles look, you can plot them like this:

plot(mecklenburg_county_shapefile)

Census Tables

I plan on doing another walk-through for finding Census tables because it can be a lengthy process. For now I will assume you know what table you want information from.

I will be combining data from two tables so if you only have one, you don’t need to do this twice.

medianfamilyincomewithchildren <- acs.lookup(endyear = 2019, table.number = "B19126") #loading data for median income

age_of_own_children <- acs.lookup(endyear = 2019, table.number = "B23008") #loading data for households with children

Variable Names and Selecting Columns

To find out what the table variable names are, you will do this first line for viewing results by variable name. It will be important for narrowing down your search and naming columns.

Since the tables can have a lot of information, selecting only the information you want to use will make a big difference. In the columns variables I created, I only wanted one variable. If you want more you will just do the same process but with additional pieces.

ex. yourdatacolumns <- yourstoredtable[1] + yourstoredtable[2] + yourstoredtable[3]

and so on for whatever you’re wanting to use.

results(age_of_own_children)$variable.name
##  [1] "Total:"                                                                       
##  [2] "Under 6 years:"                                                               
##  [3] "Under 6 years: Living with two parents:"                                      
##  [4] "Under 6 years: Living with two parents: Both parents in labor force"          
##  [5] "Under 6 years: Living with two parents: Father only in labor force"           
##  [6] "Under 6 years: Living with two parents: Mother only in labor force"           
##  [7] "Under 6 years: Living with two parents: Neither parent in labor force"        
##  [8] "Under 6 years: Living with one parent:"                                       
##  [9] "Under 6 years: Living with one parent: Living with father:"                   
## [10] "Under 6 years: Living with one parent: Living with father: In labor force"    
## [11] "Under 6 years: Living with one parent: Living with father: Not in labor force"
## [12] "Under 6 years: Living with one parent: Living with mother:"                   
## [13] "Under 6 years: Living with one parent: Living with mother: In labor force"    
## [14] "Under 6 years: Living with one parent: Living with mother: Not in labor force"
## [15] "6 to 17 years:"                                                               
## [16] "6 to 17 years: Living with two parents:"                                      
## [17] "6 to 17 years: Living with two parents: Both parents in labor force"          
## [18] "6 to 17 years: Living with two parents: Father only in labor force"           
## [19] "6 to 17 years: Living with two parents: Mother only in labor force"           
## [20] "6 to 17 years: Living with two parents: Neither parent in labor force"        
## [21] "6 to 17 years: Living with one parent:"                                       
## [22] "6 to 17 years: Living with one parent: Living with father:"                   
## [23] "6 to 17 years: Living with one parent: Living with father: In labor force"    
## [24] "6 to 17 years: Living with one parent: Living with father: Not in labor force"
## [25] "6 to 17 years: Living with one parent: Living with mother:"                   
## [26] "6 to 17 years: Living with one parent: Living with mother: In labor force"    
## [27] "6 to 17 years: Living with one parent: Living with mother: Not in labor force"
medianfamilyincomewithchildren_columns <- medianfamilyincomewithchildren[3]

age_of_own_children_columns <- age_of_own_children[4]

Fetch Specific Data

The first three lines are creating variables to use when fetching data from the ACS. While these aren’t necessary, they do help if you’re going to be using the same timespan for more projects.

Since I’m going to be combining two tables I’ve fetched two but you will only need to run it for as many as you’re pulling from.

The str() function will show you the information you will need in the next steps.

myspan <- 5 #creates variable with for length of ACS span
myendyear <- 2019 #creates variable with year to pull ACS data
mygeo <- geo.make(state = 37, county = 119, tract = "*")


my_data_medianfamilyincomewithchildren <- acs.fetch(endyear = myendyear, span = myspan, geography = mygeo, variable = medianfamilyincomewithchildren_columns)

my_data_age_of_own_children <- acs.fetch(endyear = myendyear, span = myspan, geography = mygeo, variable = age_of_own_children_columns)

str(my_data_age_of_own_children)
## Formal class 'acs' [package "acs"] with 9 slots
##   ..@ endyear       : int 2019
##   ..@ span          : int 5
##   ..@ geography     :'data.frame':   233 obs. of  4 variables:
##   .. ..$ NAME  : chr [1:233] "Census Tract 32.04, Mecklenburg County, North Carolina" "Census Tract 38.05, Mecklenburg County, North Carolina" "Census Tract 38.06, Mecklenburg County, North Carolina" "Census Tract 58.33, Mecklenburg County, North Carolina" ...
##   .. ..$ state : int [1:233] 37 37 37 37 37 37 37 37 37 37 ...
##   .. ..$ county: int [1:233] 119 119 119 119 119 119 119 119 119 119 ...
##   .. ..$ tract : chr [1:233] "003204" "003805" "003806" "005833" ...
##   ..@ acs.colnames  : chr "B23008_004"
##   ..@ modified      : logi FALSE
##   ..@ acs.units     : Factor w/ 5 levels "count","dollars",..: 1
##   ..@ currency.year : int 2019
##   ..@ estimate      : num [1:233, 1] 146 30 148 156 374 257 171 448 257 81 ...
##   .. ..- attr(*, "dimnames")=List of 2
##   .. .. ..$ : chr [1:233] "Census Tract 32.04, Mecklenburg County, North Carolina" "Census Tract 38.05, Mecklenburg County, North Carolina" "Census Tract 38.06, Mecklenburg County, North Carolina" "Census Tract 58.33, Mecklenburg County, North Carolina" ...
##   .. .. ..$ : chr "B23008_004"
##   ..@ standard.error: num [1:233, 1] 55.3 13.4 85.1 37.1 124 ...
##   .. ..- attr(*, "dimnames")=List of 2
##   .. .. ..$ : chr [1:233] "Census Tract 32.04, Mecklenburg County, North Carolina" "Census Tract 38.05, Mecklenburg County, North Carolina" "Census Tract 38.06, Mecklenburg County, North Carolina" "Census Tract 58.33, Mecklenburg County, North Carolina" ...
##   .. .. ..$ : chr "B23008_004"

Create GEOID

The previous str() function showed some information you will need here. This step will be combining the state, county, and tract codes (seen above) into a single string.

The head() function will show you what they look like so you can make sure it’s correct.

acsgeoid_medianfamilyincomewithchildren <- 
  paste0(as.character(my_data_medianfamilyincomewithchildren@geography$state),
                                       str_pad(as.character(my_data_medianfamilyincomewithchildren@geography$county),                                           3, pad='0'),
                                       str_pad(as.character(my_data_medianfamilyincomewithchildren@geography$tract),                                           6, pad='0'))

acsgeoid_age_of_own_children <- paste0(as.character(my_data_age_of_own_children@geography$state),
                                       str_pad(as.character(my_data_age_of_own_children@geography$county), 3,                                                  pad='0'),
                                       str_pad(as.character(my_data_age_of_own_children@geography$tract), 6,                                                   pad='0'))

head(acsgeoid_age_of_own_children)
## [1] "37119003204" "37119003805" "37119003806" "37119005833" "37119005841"
## [6] "37119005842"

Create Dataframe with GEOID and Targeted Data

The previous str() function shows the “estimate” that is referred to here. It’s usually the number of focus when pulling data from the Census as it is usually the amount used.

This step is creating a dataframe using the created GEOID string and the data you’re wanting to view. You can see what it looks like with the tibble() function below.

mydatadf_medianfamilyincomewithchildren <- data.frame(acsgeoid_medianfamilyincomewithchildren, my_data_medianfamilyincomewithchildren@estimate)

mydatadf_age_of_own_children <- data.frame(acsgeoid_age_of_own_children, my_data_age_of_own_children@estimate)

tibble(mydatadf_age_of_own_children)
## # A tibble: 233 x 2
##    acsgeoid_age_of_own_children B23008_004
##    <chr>                             <dbl>
##  1 37119003204                         146
##  2 37119003805                          30
##  3 37119003806                         148
##  4 37119005833                         156
##  5 37119005841                         374
##  6 37119005842                         257
##  7 37119005843                         171
##  8 37119005844                         448
##  9 37119005845                         257
## 10 37119005846                          81
## # ... with 223 more rows

Name columns

This step isn’t necessary but it is helpful if you want to rename the columns so they’re easier to understand.

Again, tibble() can be used to see what it looks like.

colnames(mydatadf_medianfamilyincomewithchildren)=c("GEOID",
                                            "median_income"
)

colnames(mydatadf_age_of_own_children)=c("GEOID",
                                         "children_under_6_years_living_with_2_parents_both_in_labor_force"
                                         )

tibble(mydatadf_age_of_own_children)
## # A tibble: 233 x 2
##    GEOID       children_under_6_years_living_with_2_parents_both_in_labor_force
##    <chr>                                                                  <dbl>
##  1 37119003204                                                              146
##  2 37119003805                                                               30
##  3 37119003806                                                              148
##  4 37119005833                                                              156
##  5 37119005841                                                              374
##  6 37119005842                                                              257
##  7 37119005843                                                              171
##  8 37119005844                                                              448
##  9 37119005845                                                              257
## 10 37119005846                                                               81
## # ... with 223 more rows

Clean Table (if necessary)

The first part of this code is used to show that there is some data that isn’t relevant. Not all tables will have information you’ll want to clean, you’ll have to look at yours to see.

In this example I wanted to change the “-666666666” median incomes into “NA” to make it look better and to avoid any issues if I wanted to analyze the numbers.

viewing_bad_data <- mydatadf_medianfamilyincomewithchildren %>%
arrange(median_income) %>%
  slice(1:10) %>%
  glimpse()
## Rows: 10
## Columns: 2
## $ GEOID         <chr> "37119000600", "37119001505", "37119004600", "3711900430~
## $ median_income <dbl> -666666666, -666666666, -666666666, -666666666, -6666666~
mydatadf_medianfamilyincomewithchildren_clean <- mydatadf_medianfamilyincomewithchildren

mydatadf_medianfamilyincomewithchildren_clean[mydatadf_medianfamilyincomewithchildren_clean < 0] <- NA

Join Tables (if necessary)

This step will only be necessary if you’re combing tables. You may also do it in a different way. I wanted to keep all rows of data so I used an inner_join()

joined_table <- inner_join(mydatadf_age_of_own_children, mydatadf_medianfamilyincomewithchildren_clean)
## Joining, by = "GEOID"
tibble(joined_table)
## # A tibble: 233 x 3
##    GEOID       children_under_6_years_living_with_2_parents_both_~ median_income
##    <chr>                                                     <dbl>         <dbl>
##  1 37119003204                                                 146        139926
##  2 37119003805                                                  30        101063
##  3 37119003806                                                 148         69825
##  4 37119005833                                                 156        138438
##  5 37119005841                                                 374        164875
##  6 37119005842                                                 257        104107
##  7 37119005843                                                 171        144583
##  8 37119005844                                                 448        165463
##  9 37119005845                                                 257        172266
## 10 37119005846                                                  81        234792
## # ... with 223 more rows

Geo Join

Here you’ll be joining the table with the geo_join() function so that you will be able to map it.

mydatamerged_joined <- geo_join(mecklenburg_county_shapefile, joined_table, "GEOID", "GEOID")

head(mydatamerged_joined)
## Simple feature collection with 6 features and 15 fields
## Geometry type: MULTIPOLYGON
## Dimension:     XY
## Bounding box:  xmin: -80.99265 ymin: 35.07495 xmax: -80.7764 ymax: 35.19951
## Geodetic CRS:  NAD83
##   STATEFP COUNTYFP TRACTCE       GEOID  NAME           NAMELSAD MTFCC FUNCSTAT
## 1      37      119  005916 37119005916 59.16 Census Tract 59.16 G5020        S
## 2      37      119  003808 37119003808 38.08 Census Tract 38.08 G5020        S
## 3      37      119  005918 37119005918 59.18 Census Tract 59.18 G5020        S
## 4      37      119  005914 37119005914 59.14 Census Tract 59.14 G5020        S
## 5      37      119  002100 37119002100    21    Census Tract 21 G5020        S
## 6      37      119  002200 37119002200    22    Census Tract 22 G5020        S
##     ALAND AWATER    INTPTLAT     INTPTLON
## 1 5027080  22224 +35.1317236 -080.9106075
## 2 1732532  53771 +35.1446598 -080.8839115
## 3 5047597  60513 +35.0894456 -080.9790206
## 4 7403759   3814 +35.1242655 -080.9726871
## 5 1588645      0 +35.1850848 -080.7855990
## 6 4342672   7869 +35.1846948 -080.8046739
##   children_under_6_years_living_with_2_parents_both_in_labor_force
## 1                                                               42
## 2                                                              112
## 3                                                              221
## 4                                                              175
## 5                                                               87
## 6                                                              223
##   median_income rank                       geometry
## 1         38426    1 MULTIPOLYGON (((-80.93156 3...
## 2         50508    1 MULTIPOLYGON (((-80.89418 3...
## 3         81324    1 MULTIPOLYGON (((-80.99265 3...
## 4        113158    1 MULTIPOLYGON (((-80.98905 3...
## 5        223056    1 MULTIPOLYGON (((-80.79383 3...
## 6        214304    1 MULTIPOLYGON (((-80.82007 3...

##Create Popup Here you will be selecting the information you will want if you decide to use a popup. This is what will be shown when the map is selected.

mypopup_joined <- paste0("GEOID: ", mydatamerged_joined$GEOID, "<br>", 
                                      "Households: ",                                   
                          round(mydatamerged_joined$children_under_6_years_living_with_2_parents_both_in_labor_force,
                                            0), "<br>",
                                      "Median Income of Married-Couple Family with Children Under 18: $",
                                        mydatamerged_joined$median_income
)

##Create Palette Here you will be deciding how you want the map colors to look. You can select a specific range (shown with the #) or use choose a range specific to the data.

mypal_joined <- colorNumeric(
  palette = "YlGnBu",
  #domain = 7000:160000
  domain = mydatamerged_joined$children_under_6_years_living_with_2_parents_both_in_labor_force
)

Location for Marker

This block is optional and will be used if you want to create a marker for the map. I’ve created a marker that will show the location of Charlotte.

myLAT <- 35.22074449075387
myLNG <- -80.83915132078283
mycentername <- "Charlotte"

Create Map

This is where it will all come together to create the map. There’s a lot going on so it’s good to read through it and see what options are all available.

mymap_joined <- leaflet() %>%
  addProviderTiles("CartoDB.Positron") %>%
  setView(myLNG, myLAT, zoom = 10) %>%
  addPolygons(data = mydatamerged_joined,
              fillColor = ~mypal_joined(children_under_6_years_living_with_2_parents_both_in_labor_force),
              color = "#b2aeae",
              fillOpacity = 0.7,
              weight = 1,
              smoothFactor = 0.2,
              popup = mypopup_joined) %>%
  
  addLegend(pal = mypal_joined,
            #values = 0:160000,
            values = mydatamerged_joined$children_under_6_years_living_with_2_parents_both_in_labor_force,
            position = "bottomright",
            title = "Households:",
            #labFormat = labelFormat(prefix = "$")
  )

mymap_joined

Embed

For embedding the map, I choose to upload it to rpubs and iframe code it provided.

This may seem like a lot but the more you do it, the easier and faster it will become. You will likely make mistakes and that’s okay! Practicing with different tables will help you learn more about what all the steps do.