mapview
We now use state capital
with longitude and latitude and
plot the capital of each state. The idea is similar to that of
ggplot
: we make the scatter plots on the existing
choropleth map using the geocode in the new sf
object
defined based on the new data set.
library(tigris)
library(mapview)
library(dplyr)
library(sf)
#invisible({capture.output({
## Download shapefile for all states into R in tigris
## states() is a function in library {tigris}
us_geo <- states(cb = F, resolution = '20m')
## load the location data
capitals <- read.csv("https://raw.githubusercontent.com/pengdsci/sta553/main/data/us-state-capitals.csv")
##
capitals_geo <- st_as_sf(capitals,
coords = c("longitude", "latitude"),
crs = 4326)
## caution: need to tell R that GEOIS should be a character variable since
## the same GEOID is character variable in the shape file us_geo with
## some leading zeros!
pop_data <- read.csv("https://raw.githubusercontent.com/pengdsci/sta553/main/data/state_population_data.csv", colClasses = c(GEOID = "character"))
## merger two data use the primary key: GEOID.
all_data <- inner_join(us_geo, pop_data, by = c("GEOID" = "GEOID"))
## we add the above layer to the previously created map
mapview(all_data, zcol = "PctChange10_20", layer.name = "Per Chg") + capitals_geo