Skip to content

Instantly share code, notes, and snippets.

@vi-enne
Created October 4, 2022 13:46
Show Gist options
  • Save vi-enne/69b4b7b34b8252c726d90e1d8b9d5eeb to your computer and use it in GitHub Desktop.
Save vi-enne/69b4b7b34b8252c726d90e1d8b9d5eeb to your computer and use it in GitHub Desktop.
library(sf)
library(ggplot2)
library(rjson)
library(dplyr)
# Source: https://rud.is/b/2018/10/10/geojson-version-of-cbc-quebec-ridings-hex-cartograms-with-example-usage-in-r/
geoJson <-
"https://gitlab.com/hrbrmstr/quebec-hex-ridings/-/raw/master/quebec-ridings.geojson"
carte <-
sf::st_read(geoJson, quiet = TRUE, stringsAsFactors = FALSE)
carte$NM_CEP[carte$NM_CEP == "Bourget"] <- "Camille-Laurin" # Changement de nom
# Source: Élections Québec https://www.dgeq.org/donnees.html
res <- fromJSON(file = "https://www.dgeq.org/resultats.json")
circ <- res$circonscriptions
n <- length(circ)
NM_CEP <- rep(NA, n)
num <- rep(NA, n)
part <- rep(NA, n)
for (i in 1:n) {
NM_CEP[i] <- circ[[i]]$nomCirconscription
num[i] <- circ[[i]]$numeroCirconscription
part[i] <- circ[[i]]$candidats[[1]]$abreviationPartiPolitique
}
fin <- data.frame(NM_CEP, num, part)
fin$part <-
ifelse(
fin$part == "C.A.Q.-E.F.L.",
"Coalition Avenir Québec",
ifelse(
fin$part == "P.L.Q./Q.L.P.",
"Parti Libéral du Québec",
ifelse(fin$part == "P.Q.", "Parti Québécois", "Québec Solidaire")
)
)
carte <- merge(carte, fin)
carte$part <-
factor(
carte$part,
levels = c(
"Coalition Avenir Québec",
"Parti Libéral du Québec",
"Québec Solidaire",
"Parti Québécois"
)
)
color = c("lightblue", "red", "orange", "darkblue")
nSeats <- data.frame(table(fin$part))
nSeats <- nSeats[order(nSeats$Freq, decreasing = T),]
colnames(nSeats)[1] <- "part"
png(
filename = "quebec2022.png",
width = 900,
height = 650,
units = 'mm',
res = 100
)
ggplot(carte) +
geom_sf(aes(fill = part)) +
geom_sf(
fill = "transparent",
color = "gray20",
size = 2,
data = . %>% group_by(region) %>% summarise()
) +
scale_fill_manual(
name = "Partis et sièges",
labels = paste0(nSeats[, 1], " ", nSeats[, 2]),
values = color
) +
coord_sf(datum = NA) +
ggthemes::theme_map() +
theme(legend.position = "bottom",
text = element_text(size = 50),
plot.title = element_text(hjust = 0.5)) +
labs(
title = paste("Élections générales québécoises du 3 octobre 2022"),
subtitle = paste0(
"Chaque hexagone représente l'une de 125 circonscriptions et les sièges correspondants à l’Assemblée Nationale"
),
caption = "V. Nicoletta @vi__enne - Source: Élections Québec"
)
dev.off()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment