1 Scatter Map with 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

2 Scatter Map Without Using sf Object

We can also use mapview() to make a scatter plot directly on the basemap without using a choropleth map as the background. This simply uses the data with longitude and latitude to make the scatter map without converting the data to an `sf’ object.

The set to be used is a regular R data frame with longitude and latitude. Two new variables were added to the merged data set to make more information geographic representation of the change to the population from 2010 to 2020.

library(mapview)
library(sf)
pop_data <- read.csv("https://raw.githubusercontent.com/pengdsci/sta553/main/data/state_population_data.csv", colClasses = c(GEOID = "character"))
capitals <- read.csv("https://raw.githubusercontent.com/pengdsci/sta553/main/data/us-state-capitals.csv")
## inner join the above two data frames
state.pop.geo <- inner_join(pop_data, capitals, by = "State")
state.pop.geo$chg.size <- abs(state.pop.geo$PctChange10_20)
chg.dir <- rep("increase", dim(state.pop.geo)[1])
chg.dir[which(state.pop.geo$PctChange10_20 < 0)] = "decrease"
state.pop.geo$chg.dir = chg.dir
#
mapview(state.pop.geo, xcol = "longitude", ycol = "latitude", 
        crs = 4269, 
        grid = FALSE, 
        na.col ="red",
        zcol = "chg.dir",
        cex = "chg.size",
        popup = TRUE, 
        legend = TRUE)