---
title: "Lab 13.1 - Gerrymandering in Michigan?"
author: "Author Goes Here"
date: "Semester Goes Here"
output: html_document
---

Notes:

- This is a rehash of the text's analysis of North Carolina. Michigan is a bit different in that its gerrymandering is harder to see due to the small, highly-populated Detroit districts.

- Cf. https://today.wayne.edu/news/2020/10/05/michigans-effort-to-end-gerrymandering-revives-a-practice-rooted-in-ancient-athens-39332


```{r echo=FALSE, message=FALSE}
library(tidyverse)
library(mdsr)
```

The goal of this exercise is build an analysis of potential gerrymandering in Michigan based on the model provided by the textbook for North Carolina.

## Loading and Wrangling the Data

See install notes for fec12 in the text (https://github.com/baumer-lab/fec12).
```{r}
library(fec12)

results_house
```


```{r}
district_elections <- results_house %>%
  mutate(district = parse_number(district_id)) %>%
  group_by(state, district) %>%
  summarize(
    N = n(),
    total_votes = sum(general_votes, na.rm = TRUE),
    d_votes = sum(ifelse(party == "D", general_votes, 0), na.rm = TRUE),
    r_votes = sum(ifelse(party == "R", general_votes, 0), na.rm = TRUE)
  ) %>%
  mutate(
    other_votes = total_votes - d_votes - r_votes,
    r_prop = r_votes / total_votes,
    winner = ifelse(r_votes > d_votes, "Republican", "Democrat")
  )
mi_results <- district_elections %>%
  filter(state == "MI")
mi_results %>%
  select(-state)
```

This is a bigger vote distribution than in North Carolina, and yet, Republicans won 9 of the 14 districts.

```{r}
mi_results %>%
  skim(total_votes) %>%
  select(-na)
```

Here is the key data. Districts 12&ndash;14 are heavily democratic and are the three most concentrated districts for either party. Then come districts 10 (Republican) and 5 (Democratic). 

```{r}
mi_results %>% 
  select(district, r_prop, winner) %>% 
  arrange(desc(r_prop))
```

The democratic winning margin in raw votes was higher in Michigan.

```{r}
mi_results %>%
  summarize(
    N = n(), 
    state_votes = sum(total_votes), 
    state_d = sum(d_votes), 
    state_r = sum(r_votes)
  ) %>%
  mutate(
    d_prop = state_d / state_votes, 
    r_prop = state_r / state_votes
  )
```

## Presenting the Data

```{r}
library(sf)
fs::path("data")
```

This code downloads and unzips the district data file used in the text.
Note that the sub-directory named by the fs::path() argument must exit.

```{r eval = FALSE}
# Can't get this to run, so just download and unzip manually.
# src <- "http://cdmaps.polisci.ucla.edu/shp/districts113.zip"
# dsn_districts <- usethis::use_zip(src, destdir = fs::path("data"))
```

When the data is downloaded/unzipped into data/districtShapes/, this code reads it more quickly.

```{r}
dsn_districts <- fs::path(fs::path_wd(), "data", "districts113", "districtShapes")

st_layers(dsn_districts)

districts <- st_read(dsn_districts, layer = "districts113") %>%
  mutate(DISTRICT = parse_number(as.character(DISTRICT))) %>% 
  janitor::clean_names()

glimpse(districts)
```

```{r}
library(sf)
library(ggspatial)

mi_shp <- districts %>%
 filter(statename == "Michigan")

mi_shp %>%
  ggplot() +
  geom_sf()

# Not sure what this non-standard stuff did for us.
# mi_shp %>%
#  st_geometry() %>%
#  plot(col = gray.colors(nrow(mi_shp)))
```

```{r}
mi_merged <- mi_shp %>%
  st_transform(4326) %>%
  inner_join(mi_results, by = c("district" = "district"))
glimpse(mi_merged)
```

```{r}
mi <- mi_merged %>%
  ggplot() +
  aes(fill = winner) +
  annotation_map_tile(zoom = 6, type = "osm") + 
  geom_sf(alpha = 0.5) +
  scale_fill_manual("Winner", values = c("blue", "red")) +
  geom_sf_label(aes(label = district), fill = "white") + 
  theme_void()
mi
```

Here's a map showing proportions.

```{r}
mi +
  aes(fill = r_prop) + 
  scale_fill_distiller(
    "Proportion\nRepublican", 
    palette = "RdBu"
#    limits = c(0.2, 0.8)
  )
```

Here are versions of these maps with better labels (N. Tammenga, Spring 2022).

```{r}
library(ggspatial)
library(ggrepel)

mi <- ggplot(data = mi_merged, 
             aes(fill = winner)) +
  annotation_map_tile(zoom = 6, 
                      type = "osm") +
  geom_sf(alpha = 0.5) +
  scale_fill_manual("Winner", 
                  values = c("blue", "red")) +
  theme_void()
  
  
mi1 <- mi + ggrepel::geom_label_repel(data = mi_merged %>%
                                   sf::st_set_geometry(NULL) %>%
                                   bind_cols(mi_merged %>% 
                                        sf::st_centroid() %>% 
                                        sf::st_coordinates() %>% as_tibble()),
                                 aes(label = district, x = X, y = Y), color = 'white')
  

mi1
```

```{r}
mi2 <- mi + 
  aes(fill = r_prop) +
  scale_fill_distiller(
    "Proportion\nRepublican",
    palette = "RdBu",
    limits = c(0.1, 0.9)
  ) +
  ggrepel::geom_label_repel(data = mi_merged %>%
                            sf::st_set_geometry(NULL) %>%
                            bind_cols(mi_merged %>% 
                                        sf::st_centroid() %>% 
                                        sf::st_coordinates() %>% as_tibble()),
                            aes(label = district, x = X, y = Y)
  )

mi2
```

## Conclusions

There is gerrymandering, but it can be hard to see in the previous maps because of the small size of the packed democratic districts. The zooming map makes them easier to see.

```{r}
library(leaflet)
pal <- colorNumeric(palette = "RdBu", domain = c(0, 1))

leaflet_mi <- leaflet(mi_merged) %>% 
  addTiles() %>%
  addPolygons(
    weight = 1, fillOpacity = 0.7, 
    color = ~pal(1 - r_prop),
    popup = ~paste("District", district, "</br>", round(r_prop, 4))
  ) %>%
  setView(lng = -85, lat = 43.5, zoom = 6.2)

leaflet_mi
```


Here's a nice summary from N. Tammenga, Spring 2022

Going back to the goal of looking for gerrymandering. As we saw in the analysis on North Carolina, many of the districts were very warped without much reason. In contrast, much of Michigan appears block-like and tends to be more uniform. However, we can see that the Detroit area is most likely dealing with gerrymandering. Blocking the city of Detroit together makes sense because it is a densely populated area. However, the branches out from Detroit are less justifiable. Most notably, a district branches out from southern Detroit to grab Ann Arbor. Essentially, while gerrymandering is likely an issue as seen in the Detroit-Ann Arbor issue, compared to North Carolina's tortured looking districts, Michigan appears to have less of an issue with gerrymandering.
