Skip to content

Instantly share code, notes, and snippets.

@briatte
Created March 28, 2026 14:18
Show Gist options
  • Select an option

  • Save briatte/7b04f7e3c78ca9b581be8a46c2a20399 to your computer and use it in GitHub Desktop.

Select an option

Save briatte/7b04f7e3c78ca9b581be8a46c2a20399 to your computer and use it in GitHub Desktop.
library(dplyr)
library(ggplot2)
library(sf)
library(sfReapportion)
library(patchwork)
# spatial points of voter addresses in Paris 20th district
data(Paris20eAddresses)
data(ParisPollingStations2012)
data(ParisIris)
data(RP_2011_CS8_Paris)
# subset geometry of polling stations (new geom, 76 polling stations)
ParisPollingStations2012 <- sf::st_as_sf(ParisPollingStations2012) %>%
dplyr::filter(arrondisse %in% c(20)) %>%
dplyr::mutate(id_brut_bv_reu = paste("75020_", num_bv))
# subset geometry of census tracts (old geom, 356 polygons)
# will throw a warning about polygons expected to be spatially constant
ParisIris <- sf::st_as_sf(ParisIris) %>%
sf::st_intersection(ParisPollingStations2012)
# this is what we're reapportioning
p1 <- ggplot(ParisIris) +
geom_sf(color = "steelblue") +
geom_sf(data = ParisPollingStations2012, color = "tomato", fill = NA) +
scale_size_area(max_size = 10) +
theme_void()
p2 <- ggplot(ParisIris) +
geom_sf(color = "steelblue") +
geom_sf(data = ParisPollingStations2012, color = "tomato", fill = NA) +
geom_sf(data = Paris20eAddresses, aes(size = nb_adresses), alpha = 1/4) +
scale_size_area(max_size = 10) +
theme_void()
ggsave("sfReapportion-20e.png", p1 + p2, width = 10, height = 8)
# subset census data to reapportion (93 distinct census tracts)
RP_2011_CS8_Paris <- dplyr::filter(RP_2011_CS8_Paris,
IRIS %in% ParisIris$DCOMIRIS)
# unweighted
r1 <- sfReapportion(ParisIris, ParisPollingStations2012, RP_2011_CS8_Paris,
"DCOMIRIS", "ID", "IRIS")
# weighted
# will throw a warning about `weight_matrix` having only been lightly tested
r2 <- sfReapportion(ParisIris, ParisPollingStations2012,
RP_2011_CS8_Paris,
"DCOMIRIS", "ID", "IRIS",
weight_matrix = Paris20eAddresses,
weight_matrix_var = "nb_adresses")
r1 <- ggplot(left_join(ParisPollingStations2012, r1, by = "ID")) +
geom_sf(color = "grey90", aes(fill = C11_POP15P_CS7)) +
scale_fill_viridis_c("CS7") +
theme_void() +
labs(title = "Weighted by area")
r2 <- ggplot(left_join(ParisPollingStations2012, r2, by = "ID")) +
geom_sf(color = "grey90", aes(fill = C11_POP15P_CS7)) +
scale_fill_viridis_c("CS7") +
theme_void() +
labs(title = "Weighted by area + addresses")
ggsave("sfReapportion-20e-results.png", r1 + r2, width = 10, height = 8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment