Files
visual-data/VT2-examples/vt2-ch7-codedata-dir/map-space-time.R
T

88 lines
1.9 KiB
R

library(sf)
library(animation)
#
# Load data
#
# State boundaries
statefp <- "data/cb_states/cb_2022_us_state_20m.shp"
statebnds <- st_read(statefp)
# Conterminous United States
inconterm <- !(statebnds$STUSPS %in% c("AK", "HI", "PR"))
conterm <- statebnds[inconterm,]
# Project map
conterm_p4s <-
"+proj=aea +lat_1=29.5 +lat_2=45.5 +lon_0=97.2w"
conterm_albers <- st_transform(conterm, conterm_p4s)
# Store locations
stores <- read.csv("data/walmart-openings-geocoded.csv",
sep=",")
walmarts <- stores[stores$store == "walmart",]
wal_sf <- st_as_sf(walmarts,
coords = c("lng", "lat"),
crs = "+proj=longlat")
wal_sf_albers <- st_transform(wal_sf, conterm_p4s)
#
# Sequence of Maps
#
# Year range
range(walmarts$year)
years <- 1962:2010
# Draw map for each year
par(mfrow = c(7, 7), mar = c(2,0,1,0), oma = c(2,2,2,2))
# par(mfrow = c(10,5), mar = c(1,0,1,0), oma = c(0,0,0,0))
for (yr in years) {
curr <- wal_sf_albers[wal_sf_albers$year <= yr,]
plot(st_geometry(conterm_albers),
border = "#cccccc", lwd = .2,
main = yr)
points(st_coordinates(curr),
col="#30437b", pch=16, cex = .2)
}
#
# Animated map
#
saveGIF({
years <- 1962:2010
par(mar = c(2,0,5,0))
for (yr in years) {
# Wal-Mart locations open on or before this year
curr <- wal_sf_albers[wal_sf_albers$year <= yr,]
# Blank map
plot(st_geometry(conterm_albers),
border = "#cccccc",
lwd = .2,
main = yr)
# Previous years
prev <- curr[curr$year != yr,]
points(st_coordinates(prev),
col="#dbe1f1", pch=20, cex = .3)
# This year
thisyear <- curr[curr$year == yr,]
points(st_coordinates(thisyear),
col="#30437b")
}
}, ani.width = 800, ani.height = 500,
interval = 0.1,
movie.name = "walmart-growth.gif")