Interactive Maps

Author

Rachel Garton

Published

April 18, 2023

Interactive Maps with MapView Package

A h/t to Sharon Machlis for turning people on to the Mapview package, and her excellent walkthroughs of it.

For the data tonight we’ll be using the tidycensus package to pull both census data, as well as geospatial boundaries. Let’s quickly review how we use it.

# uncomment to run, then recomment it out so you don't run it every time

census_api_key("2a6f8c21a30d3024e038d67d7d4eba647dc79cd4", overwrite=TRUE)
To install your API key for use in future sessions, run this function with `install = TRUE`.
#chose variables we want
myvars <- c(totalpop = "B01003_001",
            medincome = "B19013_001",
            medage = "B01002_001"
)
#pull for NC counties
nc_counties_withgeo <- get_acs(geography = "county",
                       variables = c(myvars),
                       state = "NC",
                       output = "wide",
                       geometry = TRUE)
Getting data from the 2017-2021 5-year ACS
Downloading feature geometry from the Census website.  To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.

  |                                                                            
  |                                                                      |   0%
  |                                                                            
  |                                                                      |   1%
  |                                                                            
  |=                                                                     |   1%
  |                                                                            
  |=                                                                     |   2%
  |                                                                            
  |==                                                                    |   2%
  |                                                                            
  |==                                                                    |   3%
  |                                                                            
  |===                                                                   |   4%
  |                                                                            
  |===                                                                   |   5%
  |                                                                            
  |=====                                                                 |   7%
  |                                                                            
  |=====                                                                 |   8%
  |                                                                            
  |======                                                                |   8%
  |                                                                            
  |======                                                                |   9%
  |                                                                            
  |=========                                                             |  12%
  |                                                                            
  |===========                                                           |  16%
  |                                                                            
  |=============                                                         |  19%
  |                                                                            
  |================                                                      |  23%
  |                                                                            
  |==================                                                    |  26%
  |                                                                            
  |=====================                                                 |  30%
  |                                                                            
  |=======================                                               |  33%
  |                                                                            
  |==========================                                            |  37%
  |                                                                            
  |============================                                          |  40%
  |                                                                            
  |===============================                                       |  44%
  |                                                                            
  |=================================                                     |  47%
  |                                                                            
  |===================================                                   |  51%
  |                                                                            
  |======================================                                |  54%
  |                                                                            
  |========================================                              |  58%
  |                                                                            
  |===========================================                           |  61%
  |                                                                            
  |=============================================                         |  64%
  |                                                                            
  |================================================                      |  68%
  |                                                                            
  |==================================================                    |  71%
  |                                                                            
  |====================================================                  |  75%
  |                                                                            
  |=======================================================               |  78%
  |                                                                            
  |=========================================================             |  82%
  |                                                                            
  |============================================================          |  85%
  |                                                                            
  |==============================================================        |  89%
  |                                                                            
  |=================================================================     |  92%
  |                                                                            
  |===================================================================   |  96%
  |                                                                            
  |======================================================================|  99%
  |                                                                            
  |======================================================================| 100%
nc_counties_withgeo
Simple feature collection with 100 features and 8 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -84.32187 ymin: 33.84232 xmax: -75.46062 ymax: 36.58812
Geodetic CRS:  NAD83
First 10 features:
   GEOID                               NAME totalpopE totalpopM medincomeE
1  37127        Nash County, North Carolina     94628        NA      52837
2  37043        Clay County, North Carolina     10997        NA      47155
3  37119 Mecklenburg County, North Carolina   1100984        NA      73124
4  37147        Pitt County, North Carolina    170600        NA      50422
5  37007       Anson County, North Carolina     22388        NA      39862
6  37031    Carteret County, North Carolina     67944        NA      61805
7  37163     Sampson County, North Carolina     59468        NA      45127
8  37131 Northampton County, North Carolina     17917        NA      39764
9  37053   Currituck County, North Carolina     27575        NA      79416
10 37103       Jones County, North Carolina      9326        NA      42401
   medincomeM medageE medageM                       geometry
1        1980    41.5     0.5 MULTIPOLYGON (((-78.2556 35...
2        8679    53.5     0.3 MULTIPOLYGON (((-84.00582 3...
3         840    35.4     0.1 MULTIPOLYGON (((-81.05803 3...
4        2325    32.9     0.3 MULTIPOLYGON (((-77.70069 3...
5        3340    41.6     1.1 MULTIPOLYGON (((-80.3102 34...
6        2094    49.4     0.2 MULTIPOLYGON (((-76.33014 3...
7        3225    40.2     0.4 MULTIPOLYGON (((-78.67179 3...
8        3566    50.3     0.3 MULTIPOLYGON (((-77.89977 3...
9        7406    43.2     0.6 MULTIPOLYGON (((-76.3133 36...
10       7091    48.5     1.0 MULTIPOLYGON (((-77.73078 3...
#all counties in the US
all_counties_withgeo <- get_acs(geography = "county",
                       variables = c(myvars),
                       output = "wide",
                       geometry = TRUE)
Getting data from the 2017-2021 5-year ACS
Downloading feature geometry from the Census website.  To cache shapefiles for use in future sessions, set `options(tigris_use_cache = TRUE)`.
all_counties_withgeo
Simple feature collection with 3221 features and 8 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -179.1489 ymin: 17.88328 xmax: 179.7785 ymax: 71.36516
Geodetic CRS:  NAD83
First 10 features:
   GEOID                              NAME totalpopE totalpopM medincomeE
1  20161              Riley County, Kansas     72602        NA      53296
2  19159             Ringgold County, Iowa      4739        NA      57700
3  30009            Carbon County, Montana     10488        NA      63178
4  16007           Bear Lake County, Idaho      6327        NA      60337
5  55011         Buffalo County, Wisconsin     13314        NA      61167
6  31185             York County, Nebraska     14164        NA      66337
7  08037            Eagle County, Colorado     55693        NA      91338
8  42129 Westmoreland County, Pennsylvania    355107        NA      64708
9  40079         Le Flore County, Oklahoma     48436        NA      43049
10 48053              Burnet County, Texas     48424        NA      65363
   medincomeM medageE medageM                       geometry
1        2489    25.5     0.1 MULTIPOLYGON (((-96.96095 3...
2        5058    44.3     1.0 MULTIPOLYGON (((-94.47167 4...
3        4261    50.7     0.9 MULTIPOLYGON (((-109.7987 4...
4        7039    38.9     1.1 MULTIPOLYGON (((-111.6345 4...
5        2352    46.5     0.5 MULTIPOLYGON (((-92.08384 4...
6        4128    39.5     1.2 MULTIPOLYGON (((-97.82629 4...
7        4058    37.8     0.8 MULTIPOLYGON (((-107.1137 3...
8        1350    47.1     0.2 MULTIPOLYGON (((-79.90487 4...
9        1869    38.8     0.3 MULTIPOLYGON (((-95.05996 3...
10       4694    44.7     0.3 MULTIPOLYGON (((-98.45924 3...
#remove MOE columns - they all end with "M"
nc_counties_withgeo <- nc_counties_withgeo %>%
  select(-ends_with("M"))

nc_counties_withgeo
Simple feature collection with 100 features and 5 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -84.32187 ymin: 33.84232 xmax: -75.46062 ymax: 36.58812
Geodetic CRS:  NAD83
First 10 features:
   GEOID                               NAME totalpopE medincomeE medageE
1  37127        Nash County, North Carolina     94628      52837    41.5
2  37043        Clay County, North Carolina     10997      47155    53.5
3  37119 Mecklenburg County, North Carolina   1100984      73124    35.4
4  37147        Pitt County, North Carolina    170600      50422    32.9
5  37007       Anson County, North Carolina     22388      39862    41.6
6  37031    Carteret County, North Carolina     67944      61805    49.4
7  37163     Sampson County, North Carolina     59468      45127    40.2
8  37131 Northampton County, North Carolina     17917      39764    50.3
9  37053   Currituck County, North Carolina     27575      79416    43.2
10 37103       Jones County, North Carolina      9326      42401    48.5
                         geometry
1  MULTIPOLYGON (((-78.2556 35...
2  MULTIPOLYGON (((-84.00582 3...
3  MULTIPOLYGON (((-81.05803 3...
4  MULTIPOLYGON (((-77.70069 3...
5  MULTIPOLYGON (((-80.3102 34...
6  MULTIPOLYGON (((-76.33014 3...
7  MULTIPOLYGON (((-78.67179 3...
8  MULTIPOLYGON (((-77.89977 3...
9  MULTIPOLYGON (((-76.3133 36...
10 MULTIPOLYGON (((-77.73078 3...
#remove that trailing "E"
colnames(nc_counties_withgeo) <- sub("E$", "", colnames(nc_counties_withgeo)) # $ means end of string only

nc_counties_withgeo
Simple feature collection with 100 features and 5 fields
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -84.32187 ymin: 33.84232 xmax: -75.46062 ymax: 36.58812
Geodetic CRS:  NAD83
First 10 features:
   GEOID                                NAM totalpop medincome medage
1  37127        Nash County, North Carolina    94628     52837   41.5
2  37043        Clay County, North Carolina    10997     47155   53.5
3  37119 Mecklenburg County, North Carolina  1100984     73124   35.4
4  37147        Pitt County, North Carolina   170600     50422   32.9
5  37007       Anson County, North Carolina    22388     39862   41.6
6  37031    Carteret County, North Carolina    67944     61805   49.4
7  37163     Sampson County, North Carolina    59468     45127   40.2
8  37131 Northampton County, North Carolina    17917     39764   50.3
9  37053   Currituck County, North Carolina    27575     79416   43.2
10 37103       Jones County, North Carolina     9326     42401   48.5
                         geometry
1  MULTIPOLYGON (((-78.2556 35...
2  MULTIPOLYGON (((-84.00582 3...
3  MULTIPOLYGON (((-81.05803 3...
4  MULTIPOLYGON (((-77.70069 3...
5  MULTIPOLYGON (((-80.3102 34...
6  MULTIPOLYGON (((-76.33014 3...
7  MULTIPOLYGON (((-78.67179 3...
8  MULTIPOLYGON (((-77.89977 3...
9  MULTIPOLYGON (((-76.3133 36...
10 MULTIPOLYGON (((-77.73078 3...

Mapping Virginia counties with mapview

mapview(nc_counties_withgeo, zcol = "medincome")

Customize colors

mapview(nc_counties_withgeo, zcol = "medincome", 
         col.regions = RColorBrewer::brewer.pal(9, "Greens"), 
         alpha.regions = 1)
Warning: Found less unique colors (9) than unique zcol values (100)! 
Interpolating color vector to match number of zcol values.

This map’s dark background appeared automatically, because mapview determined the map included a lot of light colors. You can turn off that feature.

mapviewOptions("basemaps.color.shuffle" = FALSE)
mapview(nc_counties_withgeo, zcol = "medincome", 
         col.regions = RColorBrewer::brewer.pal(9, "Greens"), 
         alpha.regions = 1)
Warning: Found less unique colors (9) than unique zcol values (100)! 
Interpolating color vector to match number of zcol values.

Two maps together

map_income <- mapview(nc_counties_withgeo, zcol = "medincome", 
         col.regions = RColorBrewer::brewer.pal(9, "Greens"), 
         alpha.regions = 1)
Warning: Found less unique colors (9) than unique zcol values (100)! 
Interpolating color vector to match number of zcol values.
map_age <- mapview(nc_counties_withgeo, zcol = "medage", 
         col.regions = RColorBrewer::brewer.pal(9, "Greens"), 
         alpha.regions = 1)
Warning: Found less unique colors (9) than unique zcol values (76)! 
Interpolating color vector to match number of zcol values.
sync(map_income, map_age)

Side-by-side slider to compare the two, from the leaflet.extras2 package

map_income | map_age

To turn off legends, hover text, popups

mapview(nc_counties_withgeo, zcol = "medincome", 
         col.regions = RColorBrewer::brewer.pal(9, "Greens"), 
         alpha.regions = 1,
         legend = FALSE, 
         label = FALSE, 
         popup = FALSE)
Warning: Found less unique colors (9) than unique zcol values (100)! 
Interpolating color vector to match number of zcol values.

Customize labels

mylabel <- glue::glue("{nc_counties_withgeo$NAM} {nc_counties_withgeo$medincome}")


mapview(nc_counties_withgeo, zcol = "medincome", 
         col.regions = RColorBrewer::brewer.pal(9, "Greens"), 
         alpha.regions = 1,
         label = mylabel)
Warning: Found less unique colors (9) than unique zcol values (100)! 
Interpolating color vector to match number of zcol values.

Customize popups

mypopup <- glue::glue("<strong>{nc_counties_withgeo$NAM}</strong><br />
                      Total Population: {nc_counties_withgeo$totalpop}<br />
                      Median Income: {nc_counties_withgeo$medincome}") %>% 
  lapply(htmltools::HTML)

# mylabel <- glue::glue("{all_data$State} {all_data$PctChange10_20}%") %>%
#   lapply(htmltools::HTML)
head(mypopup)
[[1]]
<strong>Nash County, North Carolina</strong><br />
Total Population: 94628<br />
Median Income: 52837

[[2]]
<strong>Clay County, North Carolina</strong><br />
Total Population: 10997<br />
Median Income: 47155

[[3]]
<strong>Mecklenburg County, North Carolina</strong><br />
Total Population: 1100984<br />
Median Income: 73124

[[4]]
<strong>Pitt County, North Carolina</strong><br />
Total Population: 170600<br />
Median Income: 50422

[[5]]
<strong>Anson County, North Carolina</strong><br />
Total Population: 22388<br />
Median Income: 39862

[[6]]
<strong>Carteret County, North Carolina</strong><br />
Total Population: 67944<br />
Median Income: 61805
mapview(nc_counties_withgeo, zcol = "medincome", 
         col.regions = RColorBrewer::brewer.pal(9, "Greens"), 
         alpha.regions = 1,
         popup = mypopup)
Warning: Found less unique colors (9) than unique zcol values (100)! 
Interpolating color vector to match number of zcol values.