Skip to content

Instantly share code, notes, and snippets.

@obrl-soil
Last active December 7, 2023 15:29
Show Gist options
  • Save obrl-soil/ad588993511d7294143406585cdf8f62 to your computer and use it in GitHub Desktop.
Save obrl-soil/ad588993511d7294143406585cdf8f62 to your computer and use it in GitHub Desktop.
Tilted and stacked maps with sf
# further to https://urbandemographics.blogspot.com/2016/04/creating-tilted-and-stacked-maps-in-r.html,
# an sf-friendly approach.
library(sf)
nc <- st_read(system.file('shape/nc.shp', package = 'sf'))
plot(nc)
sm <- matrix(c(2, 1.2, 0, 1), 2, 2)
nc_tilt <- nc
nc_tilt$geometry <- nc_tilt$geometry * sm
st_crs(nc_tilt) <- st_crs(nc)
# or,
# library(dplyr)
# nc_tilt <- mutate(nc, geometry = geometry * sm) %>%
# st_set_crs(st_crs(nc))
plot(nc_tilt[c('NAME', 'AREA', 'BIR74', 'SID74', 'NWBIR74')])
# ggplot2 approach is best accomplished with patchwork, so you don't get caught up
# in aes() issues and you don't have to screw with the geom any further
library(ggplot2)
library(patchwork)
plots <- lapply(c('NAME', 'AREA', 'BIR74', 'SID74', 'NWBIR74'), function(i) {
p <- ggplot(nc_tilt) +
geom_sf(aes_string(fill = i), show.legend = FALSE) +
theme_void()
if(is.numeric(nc_tilt[[i]])) {
p <- p + scale_fill_viridis_c()
}
p
})
Reduce(`/`, plots)
# or purrr::reduce(plots, `/`)
# R version 4.0.2 (2020-06-22)
# Platform: x86_64-w64-mingw32/x64 (64-bit)
# Running under: Windows 10 x64 (build 18363)
# purrr_0.3.4 patchwork_1.0.1 ggplot2_3.3.2 dplyr_1.0.1 sf_0.9-5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment