Skip to content

Instantly share code, notes, and snippets.

@chrishanretty
Created March 14, 2022 11:48
Show Gist options
  • Save chrishanretty/ca7c544531ec89fa2d56b7d033a8ff13 to your computer and use it in GitHub Desktop.
Save chrishanretty/ca7c544531ec89fa2d56b7d033a8ff13 to your computer and use it in GitHub Desktop.
R code to create a plot of parishes by party holding the corresponding Westminster seat
library(tidyverse)
library(rio)
library(hrbrthemes)
### (1) Get files in
### Parish to Ward
### https://geoportal.statistics.gov.uk/datasets/ons::parish-to-ward-to-local-authority-district-december-2020-lookup-in-england-and-wales-v2/about
par2ward <- read.csv("Parish_to_Ward_to_Local_Authority_District__December_2020__Lookup_in_England_and_Wales_V2.csv")
par2ward$FID <- NULL
### Ward to Westminster
### https://geoportal.statistics.gov.uk/datasets/063ccaa43b9a4f4281b3ad803c1ed2e8_0/explore
ward2pcon <- read.csv("Ward_to_Westminster_Parliamentary_Constituency_to_Local_Authority_District_to_Upper_Tier_Local_Authority__December_2020__Lookup_in_the_United_Kingdom_V2.csv")
ward2pcon$FID <- NULL
### General election results
### https://www.britishelectionstudy.com/data-objects/linked-data/
ge19 <- rio::import("BES-2019-General-Election-results-file-v1.1.xlsx")
### (2) Start merging
### Create parish to constituency
par2con <- merge(par2ward, ward2pcon,
by = c("WD20CD", "WD20NM"),
all.x = TRUE,
all.y = FALSE)
### Add on party holding constituency
par2con <- merge(par2con,
ge19,
by.x = "PCON20CD",
by.y = "ONSConstID")
### Sometimes this gives up multiple parishes because one parish straddles two wards
### Resolve this
par2con <- par2con %>%
group_by(PAR20CD, PAR20NM) %>%
summarize(nDistinct = length(unique(PCON20CD)),
nParties = length(unique(Winner19)),
isCon = all(Winner19 == "Conservative"),
party = case_when(nParties > 1 ~ "Mixed",
nParties == 1 ~ unique(Winner19)))
table(par2con$nParties)
plot.df <- par2con %>%
group_by(party) %>%
tally()
p1 <- ggplot(plot.df, aes(x = party, y = n, fill = party)) +
geom_col() +
scale_x_discrete("Party") +
scale_y_continuous("Number of parishes") +
labs(title = "Number of parishes according to\n party holding the corresponding Westminster constituency") +
scale_fill_manual(values = c("#0087DC",
"#E4003B",
"#FAA61A",
"#CCCCCC",
"#005B54",
"#CCCCCC"),
guide = "none") +
coord_flip() +
theme_ipsum()
ggsave(p1, file = "parish_control.png", width = 12, height = 7)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment