## 🎯 Objectives

In this tutorial, you will learn to

- work with map data and begin visualising it
- modify map projections


## 🔧 Preparation  

Note: you should do Preparation **_before_** the tutorial.

1. **Installing relevant R-package**

```{r, eval = FALSE}
install.packages(c("sf", "spData", "terra"))
```

2. **Get the distribution of preferences by candidate by division for the 2022 Australian Federal Election**

You can download this data here:  
   * Go to https://results.aec.gov.au
     * 2022 federal election
     * Downloads
     * Distribution of preferences by candidate by division
     
Or directly via the url here: https://results.aec.gov.au/27966/Website/Downloads/HouseDopByDivisionDownload-27966.csv

3. **Getting the electoral district geographical boundaries**
    * Go to https://www.aec.gov.au/electorates/gis/licence.htm to agree with the license
    * Download the ESRI (.shp) zip file for Victoria where Federal election boundary applied in 2022.  

4. **Look up the colours of the current political parties**   
  * Go to https://handbook.aph.gov.au/StatisticalInformation/Parties
  * Filter your results to Victoria and for the most recent parliament elected

5. Run the following code if you use Mac:

```{r}
# for speeding up geom_sf
if (!identical(getOption("bitmapType"), "cairo") && isTRUE(capabilities()[["cairo"]])) {
  options(bitmapType = "cairo")
}
```

## 🤺 Exercise 5A

**Download, combine and wrangle the election data so it is ready for mapping!**. 
We will need this for exercise part 5B.

1. Load the packages you need

```{r, message = FALSE, warning = FALSE}
library(tidyverse)
library(sf)
```

2. Import the election data   
*Note here we show you an example how you can directly download the data from a url instead of saving the data and reading it from a .csv*

```{r, message = FALSE, warning = FALSE}
url = "https://results.aec.gov.au/27966/Website/Downloads/HouseDopByDivisionDownload-27966.csv"

election_data <- read_csv(url,
  skip = 1
) 
```

Use the help menu `?read_csv` or ask your tutor why we need to set `skip=1`.

3. Wrangle your data so we only keep the winners from the election. 
We will also use string manipulation to change the division names be in capital letters. 

```{r, message = FALSE, warning = FALSE}
election_data = election_data |>
  # Select winning candidate only
  filter(CalculationType == "Preference Count" &
    Elected == "Y" &
    CountNumber == 0) |>
  # make division name upper case so
  # it can be joined later with map data
  mutate(DivisionNm = toupper(DivisionNm))
```

Again look a the help menu to see examples of how `?toupper` works.

4. Read the map data using the code below. 
**Note we do not use `read_csv` here. We need to use `read_sf` as this is a map.**

```{r}
data_path = "data/vic-july-2021-esri/E_VIC21_region.shp" 
vic_election_map <- read_sf(here::here(data_path)) %>%
  # to match up with election data
  mutate(DivisionNm = toupper(Elect_div))
```

5. Combine the election data with the election boundaries. 

```{r}
vic_election_map = vic_election_map |>
  left_join(election_data, by = "DivisionNm")
```

You can refresh how to combine to data sets together by reviewing the [tidyverse cheat sheet](https://rstudio.github.io/cheatsheets/tidyr.pdf).

6. Determine an appropriate colour for the political parties. 
We will need these to colour code our map.

How many and which political parties do we need colours for?

```{r}
election_data |> 
  filter(StateAb == "VIC") |> 
  select(PartyAb) |> 
  distinct(PartyAb)
```

Using the parliamentary handbook, we can match the political party with their associated colour.

```{r}
party_colors <- c(
  "ALP" = "#DE3533",
  "GVIC" = "#10C25B",
  "IND" = "#000000",
  "LP" = "#0047AB",
  "NP" = "#FFFF00"
)

```

You can change these if you'd like to. Many of the inner city independents used the teal colour.

```{r vicmap19, eval = FALSE, echo = FALSE}
vic_election_map |>
  ggplot() +
  geom_sf(aes(geometry = geometry, fill = PartyAb),
    color = "white"
  ) +
  coord_sf(xlim = c(144.8, 145.2), ylim = c(-38.1, -37.6)) +
  scale_fill_manual(values = party_colors) +
  ggtitle("Winners of Australian Federal Election in 2019",
    subtitle = "Victoria"
  )
```

## 🤺 Exercise 5B

**Draw a map of Victoria and colour the electorate districts with the political party that won that district in the 2022 federal election.**  

a) Draw a map that looks like below. 

```{r vicmap19, eval = TRUE, echo = FALSE}
```

To do this we need to use mapping functions that work with `ggplot2`.

* The function `geom_sf` is used to define the aesthetics of how to plot the map. 

* The function `coord_sf` is used to define the coordinate range of the plot. 

<details style = "padding-left:50px;">
<summary>Hint 1</summary>

```{r hint1, eval = F, echo = TRUE}
vic_election_map |>
  ggplot() +
  geom_sf(aes(geometry = ???, fill = ???), color = "black") 
```

</details>

<details style = "padding-left:50px;">
<summary>Hint 2</summary>

```{r hint2, eval = F, echo = TRUE}
vic_election_map |>
  ggplot() +
  geom_sf(aes(geometry = geometry, fill = PartyAb), color = "black") + 
  coord_sf(xlim = c(???, ???), ylim = c(???, ???)) +
```

</details>

<details style = "padding-left:50px;">
<summary>Solution</summary>

```{r vicmap19, eval = F, echo = T}
```

</details>

<br>

b) Modify the map drawn in a. so that the legend only shows the parties shown in the visualisation.

You may find the function `st_crop` useful here.

<details style = "padding-left:50px;">
<summary>Hint 3</summary>

```{r hint3, eval = F, echo = TRUE}
vic_election_map |>
    st_crop(xmin = ???, xmax = ???,
          ymin = ???, ymax = ???)
```

</details>

c) Finally add the text labels of the name of the electoral division for Melbourne, Menzies and Macnamara, like below.

The function `geom_sf_label` can be used to add labels to a map. 

<details style = "padding-left:50px;">
<summary>Hint 4</summary>

```{r hint4, eval = F, echo = TRUE}
vic_map_subset = vic_election_map %>% 
      filter(Elect_div %in% c("Melbourne", "Menzies", "Macnamara"))
             
vic_election_map |>
  ggplot() +
  geom_sf(aes(geometry = geometry), color = "black") + 
  geom_sf_label(data = vic_map_subset, aes(label = ???, geometry = ???))
```

</details>

## 🗺 Exercise 5C 

**Learn to modify the map projection**
The world is not flat. Let's learn how to deal with that in the mapping world.

Load the world map data contained in `spData`. 

```{r}
data(world, package = "spData")
```

a. Plot the map data `world` using `ggplot2`. 

```{r world-map, echo = FALSE}
ggplot(world) +
  geom_sf()
```

b. Mollweide projection is a map projection that preserves area relationships. Apply this projection by setting`crs = "+proj=moll"` in the `st_transform` function and visualise the result.

```{r moll, echo = FALSE}
world %>%
  st_transform(crs = "+proj=moll") %>%
  ggplot() +
  geom_sf()
```

c. Modify the projection so that it transforms the coordinates to the Lambert azimuthal equal-area projection with Australia in the center (25.27°S, 133.78°E).

```{r laea, echo = FALSE}
world %>%
  st_transform(crs = "+proj=laea +x_0=0 +y_0=0 +lon_0=133.78 +lat_0=-25.27") %>%
  ggplot() +
  geom_sf()
```

<details style = "padding-left:50px;">
<summary>Stuck on where to start:</summary>

```{r hint5, eval = F, echo = TRUE}
## Look at the last example in the help 
?geom_sf
```

</details>

#### Material originally developed by Dr. Emi Tanaka and maintained by Dr. Kate Saunders
