Last active
July 1, 2023 00:01
-
-
Save stephhazlitt/bdf76097b1a2bb2531103b0234884b15 to your computer and use it in GitHub Desktop.
Example choropleth using {bcmaps} & data from the B.C. Data Catalogue sourced with {bcdata}
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
library(bcdata) #get data from the BC Data Catalogue | |
library(bcmaps) #get maps | |
library(tidyr) #clean popn data file | |
library(dplyr) #summarize data | |
library(stringr) #clean and align RD names | |
library(ggplot2) #make plot | |
library(sf) #clip RD with BC boundaries | |
#get and tidy some population change data from the BC Data Catalogue | |
rd_popn <- bcdc_get_data( | |
"bc-population-estimates", | |
sheet = "Mun-RD", | |
skip = 2) |> | |
janitor::clean_names() |> | |
select(-sgc) |> | |
drop_na("name") |> | |
filter(area_type %in% c("RD", "R")) |> | |
mutate(name = tolower(name), | |
name = str_replace(name, " ", "-")) | |
# get the RD map and match RD names to popn data file (hardest part!) | |
rdm <- combine_nr_rd() |> | |
mutate( | |
name = str_remove(ADMIN_AREA_NAME, "Regional District of "), | |
name = str_remove(name, " Regional District") | |
) |> | |
mutate(name = tolower(name), | |
name = str_replace(name, " ", "-")) |> | |
mutate( | |
name = case_when( | |
name == "comox-valley" ~ "comox", | |
name == "stikine-region (unincorporated)" ~ "stikine", | |
name == "northern-rockies regional municipality" ~ "northern-rockies", | |
.default = name | |
) | |
) |> | |
st_intersection(bc_bound_hres()) |> #clip RDs with bc boundary file | |
rmapshaper::ms_simplify(keep_shapes = TRUE) |> | |
st_make_valid() | |
# join data and calculate % change | |
df <- rdm |> | |
left_join(rd_popn, keep = TRUE) |> | |
mutate(change = x2019-x2011, | |
change2 = change/x2019, | |
percent_change = round(100 * change2, digits = 2)) | |
# make a choropleth map | |
ggplot() + | |
geom_sf(data = df, aes(fill = percent_change)) + | |
labs(fill = "Population Change\n2011-2019 (%)") + | |
theme_minimal() + | |
coord_sf(datum = NA) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment