1

I am trying plot county level maps. I came across a tutorial that uses the sf package and the tmap package. Using ?st_read, it shows an example of how to get county level data using North Carolina as an example, using the following code -

nc = st_read(system.file("shape/nc.shp", package="sf"))

I used the code above to plot county level data for NC, however I am not sure how to get the data for other states. I have tried replacing the nc.shp with sc.shp or va.shp, etc, however I get the following error - Error: Fill argument neither colors nor valid variable name(s).

How do I extract the data for other states, or preferable "all" states. I would like to be able to plot the map for the entire US, regionally (north, south, east, west) and also multiple states within a region.

Here is some reproducible code for the map I created -

library(tmap)
library(tmaptools)
library(leaflet)
library(tidyverse)

options(scipen = 999)

nc_data <- st_read(system.file("shape/nc.shp", package="sf")) %>% 
  mutate(Code = case_when(
    AREA <= 0.07 ~ "Label 1", TRUE ~ "Label 2"
  ))
  
tm_shape(nc_data)+
  tm_polygons("Code", id = "NAME", palette = "Blues")

tmap_mode("view")
tmap_last()

Again, how do I plot this for other states and multiple states?

The Rookie
  • 877
  • 8
  • 15

1 Answers1

1

The 'nc' data is included as example data with the sf package, so you'll have to get data for other states in another manner.

There are a few ways to get county & state level shapefiles to plot. Urbnmapr (https://github.com/UrbanInstitute/urbnmapr) is the one I used below.

library(tidyverse)
library(sf)
#> Linking to GEOS 3.9.0, GDAL 3.2.1, PROJ 7.2.1
library(urbnmapr)
library(tmap)

us_counties <- get_urbn_map(map = 'counties', sf = TRUE)

us_counties <- us_counties %>%
  mutate(area_m_sq = st_area(.))

tmap_mode('plot')
#> tmap mode set to plotting
tm_shape(us_counties) + 
  tm_polygons('area_m_sq', palette = 'Blues')

Created on 2021-02-19 by the reprex package (v1.0.0)

urbnmapr moves HI and AK to the usual inset spot south of the western US. If that's a problem, you might have better luck getting the data from the tigris package https://github.com/walkerke/tigris.

mrhellmann
  • 5,069
  • 11
  • 38