rr-sftmapusmap

Tmap: Cannot create school district map for national level


I want to plot school districts on a national map in R using the library Tmap. I used a shapefile from the official website, the National Center for Education Statistics, for school district boundaries. Please note that I used the 2019 file instead of the latest one, and you can download this file from Single Composite File in the link mentioned earlier. I first tried with one state, Utah, and everything went well without any problems. My code to plot this map and the reference for the national map (from Bloomberg Citylab) is following;

library (sf)
library (tmap)
map <- st_read(".../schooldistrict_sy1819_tl19.shp")
ut <- map[map$STATEFP == 49, ]
tm_shape(ut) + tm_borders()

enter image description here enter image description here

However, I encountered an error when I tried to make the national map. I used this code and got the following error.

tm_shape(map) + tm_borders()
Error: Shape contains invalid polygons. Please fix it or set tmap_options(check.and.fix = TRUE) and rerun the plot

Of course, I did some research. One website suggested that the following error occurred because of invalid geometries. I checked and tried to make these valid, but I got the same mistake as the first time I did. I attempted to solve this problem with the following code.

sum(!st_is_valid(map$geometry))
[1] 858
st_make_valid(map$geometry)
Geometry set for 13315 features 
Geometry type: MULTIPOLYGON
Dimension:     XY
Bounding box:  xmin: -179.1686 ymin: -14.5487 xmax: 179.7487 ymax: 71.38961
Geodetic CRS:  NAD83
First 5 geometries:
MULTIPOLYGON (((-80.11417 26.07902, -80.11423 2...
MULTIPOLYGON (((-82.19919 26.77353, -82.19748 2...
MULTIPOLYGON (((-81.45356 25.80323, -81.45388 2...
MULTIPOLYGON (((-80.39962 25.25725, -80.40002 2...
MULTIPOLYGON (((-81.56409 27.34066, -81.56423 2...
 
tm_shape(map) + tm_borders()
Error: Shape contains invalid polygons. Please fix it or set tmap_options(check.and.fix = TRUE) and rerun the plot

Since I was blank about the geometry in R, I totally have no idea how to make it works. If anyone has done this before, could you please share any advice/ suggestions regarding this? Any idea to solve this problem would be appreciated. Thank you so much for reading my question!


Solution

  • Thanks to @mrhellmann, who figured out the minor mistake I made, you need to assign the map data to a new variable after using st_make_valid. I used the following code to plot the district-level data into the nationwide map.

    library (SF)
    library (tmap)
    map <- st_read(".../schooldistrict_sy1819_tl19.shp")
    map2 <- st_make_valid(map$geometry)
    tm_shape(map2) + tm_borders()