Skip to content

Instantly share code, notes, and snippets.

@edonnachie
Last active May 9, 2022 21:57
Show Gist options
  • Save edonnachie/58aa15f9068765c89a08c42e69a134ce to your computer and use it in GitHub Desktop.
Save edonnachie/58aa15f9068765c89a08c42e69a134ce to your computer and use it in GitHub Desktop.
Demonstration of how to overlay one region onto another using R and sf
library(sf)
library(ggplot2)
# Data from https://www.geoboundaries.org/index.html#getdata
de2 <- read_sf("data/geoBoundaries-DEU-ADM2-all/geoBoundaries-DEU-ADM2_simplified.shp")
# Extract Munich and Berlin to separate objects
munich <- dplyr::filter(de2, DistrictCo == "09162")
berlin <- dplyr::filter(de2, DistrictCo == "11000")
# Find the centroids of each city
berlin_centre <- berlin |>
st_centroid() |>
st_geometry()
munich_centre <- munich |>
st_centroid() |>
st_geometry()
# Use the centroids to calculate the shift required
# to move Munich to the centre of Berlin
coord_shift <- (berlin_centre - munich_centre)
# Make a new Munich shifted up to Berlin
# The CRS goes missing and needs to be specified again
munich_overlay <- munich
st_geometry(munich_overlay) <- st_geometry(munich_overlay) + coord_shift
st_crs(munich_overlay) <- "EPSG:4326"
# Plot
ggplot() +
geom_sf(data = berlin, colour = "#377EB8") +
geom_sf(data = munich_overlay, colour = "#E41A1C") +
coord_sf() +
theme_minimal() +
labs(
title = "How does <span style='color:#E41A1C;'>Munich</span> compare to <span style='color:#377EB8;'>Berlin</span>?",
caption = "Map data: www.geoboundaries.org\nVisualisation: github.com/edonnachie"
) +
theme(plot.title = ggtext::element_markdown(size = 12))
ggsave(filename = "berlin_munich.png",
type = "cairo", bg = "white",
width = 10, height = 10, units = "cm", dpi = 300)
@edonnachie
Copy link
Author

berlin_munich

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment