So I have a data frame in R called obesity_map which basically gives me the state, county, and obesity rate per county. It looks more or less like this:
obesi
I'm a little new at using TMAP and Spatial data, but figured I would post as a follow up to Martijn Tennekes. Using his advice I ran into an error in the second map (with the state borders). When running this line of code:
US_state <- unionSpatialPolygons(US,US$STATE)
I kept getting this error: "Error in unionSpatialPolygons(US, US$STATE) : not a SpatialPolygons object"
In order to rectify I had to use a different variable and run it as a Spatial Polygon Data Frame:
US <- read_shape("gz_2010_us_050_00_20m.shp")
US2<-readShapeSpatial("gz_2010_us_050_00_20m.shp")
US <- US[!(US$STATE %in% c("02","15","72")),]
US$FIPS <- paste0(US$STATE, US$COUNTY)
US <- append_data(US, med_inc_df, key.shp = "FIPS", key.data = "GEOID")
#the difference is here:
US_states <- unionSpatialPolygons(US2, US2$STATE)
tm_shape(US, projection="+init=epsg:2163") +
tm_polygons("estimate", border.col = "grey30", title="") +
tm_shape(US_states) +
tm_borders(lwd=2, col = "black", alpha = .5) +
tm_layout(title="2016 Median Income by County",
title.position = c("center", "top"),
legend.text.size=1)
My Map