---
title: "R Notebook"
output:
  html_document:
    df_print: paged
---

Data from `https://dait.interno.gov.it/elezioni/open-data/dati-elezioni-europee-26-maggio-2019`

```{r}
library(tidyverse)
library(sf)
library(geogrid)
library(tilemaps)
library(janitor)
library(rnaturalearth)

Sys.setlocale("LC_ALL","EN_US")

theme_set(theme_void())

proj <- "+proj=merc"
```


```{r}
votes <- read_delim("data/europee2019_scrutini_area_italia.csv",
           delim = ";") %>%
  clean_names() %>%
  mutate(name = str_to_lower(provincia)) %>%
  select(name, party=lista, votes=voti_lista) %>%
  group_by(name, party) %>%
  summarise(votes = sum(votes)) %>%
  ungroup() %>%
  group_by(name) %>%
  mutate(perc = votes / sum(votes)) %>%
  arrange(name, desc(perc))
```

```{r}
provinces <- ne_states(country="Italy", returnclass="sf") %>%
  st_transform(proj) %>%
  mutate(
    name = str_to_lower(name),
    name = case_when(
      name == "aoste" ~ "aosta",
      name == "bozen" ~ "bolzano",
      name == "turin" ~ "torino",
      name == "forlì-cesena" ~ "forli'-cesena",
      name == "barletta-andria trani" ~ "barletta-andria-trani",
      name == "crotene" ~ "crotone",
      name == "oristrano" ~ "oristano",
      name == "monza e brianza" ~ "monza e della brianza",
      name == "reggio emilia" ~ "reggio nell' emilia",
      # Fix Sardegna provinces
      name == "carbonia-iglesias" ~ "sud sardegna",
      name == "olbia-tempio" ~ "sassari",
      name == "medio campidano" ~ "sud sardegna",
      name == "ogliastra" ~ "nuoro",
      TRUE ~ name
    )
  ) %>%
  group_by(region, name) %>%
  summarise() %>%
  ungroup() %>%
  inner_join(votes, by="name") 

ggplot(provinces) +
  geom_sf()
```

```{r}
scale_politics <- function() {
  scale_color_manual(values=c(
    #"LEGA SALVINI PREMIER"="#0e4d92", 
    "LEGA SALVINI PREMIER"="steelblue", 
    "MOVIMENTO 5 STELLE"="#c0ac00",
    "PARTITO DEMOCRATICO"="#cb2a1d",
    "SVP"="#60a862"
  ), aesthetics = c('colour', 'fill'))
}
```

```{r}
provinces %>%
  group_by(name) %>%
  slice(which.max(perc)) %>%
  ggplot(aes(fill=party)) +
  geom_sf() +
  scale_politics()
```

```{r}
hex_mainland <- provinces %>%
  filter(!(region %in% c("Sicily", "Sardegna"))) %>%
  group_by(name) %>%
  slice(which.max(perc)) %>%
  ungroup() %>%
  st_transform(proj) %>%
  mutate(tile_map = generate_map(geometry, square=FALSE))

hex_sicily <- provinces %>%
  filter(region=="Sicily") %>%
  group_by(name) %>%
  slice(which.max(perc)) %>%
  ungroup() %>%
  st_transform(proj) %>%
  mutate(tile_map = generate_map(geometry, square=FALSE))

hex_sardegna <- provinces %>%
  filter(region=="Sardegna") %>%
  group_by(name) %>%
  slice(which.max(perc)) %>%
  ungroup() %>%
  st_transform(proj) %>%
  mutate(tile_map = generate_map(geometry, square=FALSE))

hexagons <- bind_rows(hex_mainland, hex_sicily, hex_sardegna)

ggplot(hexagons, aes(geometry=tile_map, fill=party)) +
  geom_sf() +
  scale_politics()
```

```{r}
margins <- provinces %>%
  st_transform(proj) %>%
  group_by(name) %>%
  arrange(desc(perc)) %>%
  mutate(margin = perc - lead(perc)) %>%
  mutate(centroid = st_centroid(geometry)) %>%
  slice(which.max(perc))

ggplot(margins, aes(geometry=centroid, size=margin, color=party)) +
  stat_sf_coordinates(geom="point") +
  scale_size_binned_area(max_size = 7) +
  scale_politics()
```

```{r}
seats_totals <- tribble(
  ~id, ~name, ~total_seats,
  1, "Italia nord-occidentale", 20,
  2, "Italia nord-orientale", 15,
  3, "Italia centrale", 15,
  4, "Italia meridionale", 18,
  5, "Italia insulare", 8
)

seats <- ne_states(country="italy", returnclass="sf") %>%
  st_transform(proj) %>%
  group_by(region) %>%
  summarise() %>%
  mutate(id = case_when(
      region == "Abruzzo" ~ 4,
      region == "Apulia" ~ 4,
      region == "Basilicata" ~ 4,
      region == "Calabria" ~ 4,
      region == "Campania" ~ 4,
      region == "Emilia-Romagna" ~ 2,
      region == "Friuli-Venezia Giulia" ~ 2,
      region == "Lazio" ~ 3,
      region == "Liguria" ~ 1,
      region == "Lombardia" ~ 1,
      region == "Marche" ~ 3,
      region == "Molise" ~ 4,
      region == "Piemonte" ~ 1,
      region == "Sardegna" ~ 5,
      region == "Sicily" ~ 5,
      region == "Toscana" ~ 3,
      region == "Trentino-Alto Adige" ~ 2,
      region == "Umbria" ~ 3,
      region == "Valle d'Aosta" ~ 1,
      region == "Veneto" ~ 2
    )
  ) %>% 
  group_by(id) %>%
  summarise() %>%
  inner_join(seats_totals)

grid <- st_make_grid(seats, square = FALSE, cellsize=.8) %>%
  st_as_sf() %>%
  mutate(id = row_number()) %>%
  mutate(
    id = case_when(
      # Macro region 1
      id %in% c(1,2,3,4,5,7,8,11,12,16,20,17,13,21,26,20,25,21,36,32,31,39) ~ 1,
      # Macro region 2
      id %in% c(35,42,51,47,59,43,52,66,80,40,48,60,74,53,67) ~ 2,
      # Macro region 3
      id %in% c(30,34,38,46,58,72,41,50,64,79,45,57,71,63,78) ~ 3,
      # Macro region 4
      id %in% c(84,90,96,100,108,83,95,104,111,115,119,99,107,113,120,110,112,109) ~ 4,
      # Macro region 5
      id %in% c(15,18,19,23,75,88,81,93) ~ 5
    )
  ) %>%
  drop_na(id)
```

```{r}
seats <- read_sf("data_files/euro_elections_seats.shp")
ggplot(seats) + 
  geom_sf(size=.1) +
  geom_sf(data=group_by(seats, id) %>% summarise(), fill=NA)
```

```{r}
euro_seat_votes <- tribble(
  ~id, ~party, ~seats,
  1, "Lega", 9,
  1, "PD", 5,
  1, "M5S", 2,
  1, "FI", 2,
  1, "FdI", 2,
  
  2, "Lega", 7,
  2, "PD", 4,
  2, "M5S", 2,
  2, "FI", 0,
  2, "FdI", 1,
  2, "SVP", 1,
  
  3, "Lega", 6,
  3, "PD", 4,
  3, "M5S", 2,
  3, "FI", 2,
  3, "FdI", 1,
  
  4, "Lega", 5,
  4, "PD", 4,
  4, "M5S", 6,
  4, "FI", 1,
  4, "FdI", 1,
  
  5, "Lega", 2,
  5, "PD", 2,
  5, "M5S", 2,
  5, "FI", 1,
  5, "FdI", 1
) %>%
  inner_join(seats_totals)
euro_seat_votes
```

```{r}
euro_indices <- euro_seat_votes %>%
  group_by(id, name) %>%
  arrange(name, desc(seats)) %>%
  mutate(
    end = cumsum(seats),
    start = lag(end) + 1
  ) %>%
  replace_na(list(start=1)) %>%
  group_by(id, name, party) %>%
  summarise(index = start:end)
euro_indices
```

```{r}
seats %>%
  group_by(id) %>%
  mutate(index = row_number()) %>%
  inner_join(euro_indices) %>%
  ggplot() +
  geom_sf(aes(fill=party), size=.1) +
  geom_sf(data=group_by(seats, id) %>% summarise(), 
          fill=NA,
          color="white",
          size=.5) +
  scale_color_manual(values=c(
    "Lega"="steelblue", 
    "M5S"="#c0ac00",
    "PD"="#cb2a1d",
    "SVP"="#60a862",
    "FI" = "blue",
    "FdI" = "black"
  ), aesthetics = c('colour', 'fill')) +
  labs(caption="Sardegna and Sicilia are part of the same electoral college")
  #stat_sf_coordinates(aes(label=index), geom="text")
```















