The polygons are plotted using the US census county file:
https://www2.census.gov/geo/tiger/GENZ2018/shp/cb_2018_us_county_500k.zip
Read into R with :
UScounties <- rgdal::readOGR(dsn = paste0(getwd(),"/mapdata/Counties"),
layer = "cb_2018_us_county_500k")
> head(UScounties@data)
STATEFP COUNTYFP COUNTYNS AFFGEOID **GEOID** NAME LSAD ALAND AWATER
0 21 007 00516850 0500000US21007 21007 Ballard 06 639387454 69473325
1 21 017 00516855 0500000US21017 21017 Bourbon 06 750439351 4829777
2 21 031 00516862 0500000US21031 21031 Butler 06 1103571974 13943044
3 21 065 00516879 0500000US21065 21065 Estill 06 655509930 6516335
4 21 069 00516881 0500000US21069 21069 Fleming 06 902727151 7182793
5 21 093 00516893 0500000US21093 21093 Hardin 06 1614569777 17463238
spTransform...
UScounties <- spTransform(UScounties,CRS("+init=epsg:4326"))
And then the correct map is drawn when plotting with leaflet.
Now, I want to join other county data by GEOID, e.g., Unemployment data from USDA.gov:
https://www.ers.usda.gov/webdocs/DataFiles/48747/Unemployment.xlsx?v=307.4
UScounties@data <- merge(UScounties@data,Unemployment, by = c("GEOID"= "FIPS_Code") )
Check if the merge is correct:
> UScounties@data[UScounties@data$FIPS == 36013,c(1:7,11:12)]
FIPS STATEFP COUNTYFP COUNTYNS AFFGEOID GEOID NAME State Area_name
1834 36013 36 013 00974105 0500000US36013 36013 Chautauqua NY Chautauqua County, NY
Use Leaflet to plot counties with popups:
UScounties@data$AWATER <- as.numeric(UScounties@data$AWATER)
pal <- colorNumeric(
palette = "Blues",
domain = UScounties$AWATER)
leaflet() %>%
addProviderTiles(providers$CartoDB.DarkMatter) %>%
addPolygons(data = UScounties,
color = "white",
fillColor = pal(UScounties$AWATER),
weight = 1,
smoothFactor = 0.2,
opacity = .77,
fillOpacity = 0.9,
highlightOptions = highlightOptions(color = "white",
weight = 2,
bringToFront = TRUE),
labelOptions = labelOptions(style = list("font-weight" = "normal", padding= "3px 8px"),
textsize = "15 px",
direction = "auto"),
popup = paste("County: ", UScounties@data$NAME, "<br>",
"Land: ", UScounties$ALAND, "<br>",
"Water: ", UScounties$AWATER, "<br>")) %>%
addLegend("bottomleft",
title = "Legend",
pal = pal,
values = UScounties$AWATER,
opacity = .4)
Check map for correct plot:
Data for this polygon is displayed incorrectly.
Anyone come across this before?