Friday, July 24, 2020

Playground with election data.

Loading libs

pacman::p_load(tidyverse, readxl, janitor, sf)

Loading data from https://wybory.gov.pl/prezydent20200628/pl/dane_w_arkuszach

df_raw <- 
  read_xlsx(
    path = "dane/wyniki_gl_na_kand_po_wojewodztwach_utf8.xlsx"
    ) %>% 
  clean_names() %>% 
  # kod teryt - we need first two digits for province
  mutate(kod_teryt=str_sub(kod_teryt, end = 2))

Loading shp files from https://gis-support.pl/granice-administracyjne/

map <-
  st_read("dane/Województwa.shp") %>%
  st_make_valid() %>% 
  # if cropping needed
  # %>%
  # st_crop(
  #   xmin = -20,
  #   xmax = 45,
  #   ymin = 30,
  #   ymax = 120
  # ) %>% 
  # we need only province code and geometry
select(kod_teryt = JPT_KOD_JE) 
## Reading layer `WojewĂłdztwa' from data source `C:\Users\jkotows2\Desktop\_r_wybory\dane\WojewĂłdztwa.shp' using driver `ESRI Shapefile'
## Simple feature collection with 16 features and 29 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: 14.12288 ymin: 49.00205 xmax: 24.14578 ymax: 54.83642
## proj4string:    +proj=longlat +ellps=GRS80 +no_defs

Joining shp with data

df <- merge(map, df_raw, by.x="kod_teryt", by.y="kod_teryt") 

Plot choropleth

p <- ggplot(df) +
  geom_sf(aes( fill=liczba_glosow_niewaznych)) +
  geom_sf_label(aes(label = 
                      paste0(scales::number(liczba_glosow_niewaznych, accuracy = 1))), size = 2.97, alpha = 0.7) +
  theme_void()+
  labs(title = "Presidential elections Poland 2020",
       subtitle = "Void votes",
       caption = "Source: PKW, Author: Jacek Kotowski"
       )+
  scale_fill_viridis_c(
    option = "cividis", 
    trans = "log", 
    direction = -1) +
   theme(legend.position = "none") 
  

p

Ranking void votes

df %>% ggplot(aes(fct_reorder(wojewodztwo, liczba_glosow_niewaznych), liczba_glosow_niewaznych)) +
  geom_col(fill = "blue", color = "gray", alpha = 0.1, width = 0.7) + 
  geom_text(aes(label = paste0(scales::number(liczba_glosow_niewaznych, accuracy = 1)))) +
  coord_flip() +
  theme_light() +
  labs(
    title="Poland Presidential Elections 2020",
    subtitle = "Void votes",
    caption = "Source: PKW, Author: Jacek Kotowski",
    x = "",
    y = ""
      )  

No comments:

Post a Comment

An example of a bat file that shows dialogues

@echo off setlocal :: Prompt user for input file names set /p jpgfile="Enter the name of the JPG file: " set /p archive="Ent...