---
title: "Comp/Stat 112: Spatial Visualization"
author: "INSERT STUDENT NAME HERE (COLLABORATOR NAMES HERE)"
output:
  bookdown::html_document2:
    split_by: none
    toc: yes
    toc_depth: 3
    toc_float:
      toc_collapsed: true
    number_sections: false
        code_download: true
---

```{r 06_setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, error = TRUE)
library(tidyverse)
library(ggplot2)
library(gplots)
library(maps) # for map data  #install.packages('maps')
library(ggmap) # for mapping points on maps  #install.packages('ggmap')
library(RColorBrewer) # for color palettes #install.packages('RColorBrewer')
library(leaflet) # for highly customizable mapping  #install.packages('leaflet')
library(ggthemes) # for more themes (including theme_map())  #install.packages('ggthemes')
library(usdata) #install.packages('usdata')
```

# Spatial Visualizations

## Plotting Points on a Map {-}

### Starbucks Example {-}

The `Starbucks` data, compiled by Danny Kaplan, contains information about every Starbucks in the world at the time the data were collected. It includes the `Latitude` and `Longitude` of each location. 

```{r}
# Starbucks locations
Starbucks <- read_csv("https://milnel2.github.io/112_spring_2023/data/starbucks.csv")
```

### Example: Starbucks as Points {-}

```{example}
Now it is your turn to work with the Starbucks data.
```

a. Add an aesthetic to the world map that sets the color of the points according to the ownership type. What, if anything, can you deduce from this visualization? 

```{r fig.alt = 'Alt Text Here'}
#a)

```

b. Construct a new map of Starbucks locations in the Twin Cities metro area (approximately the five county metro area).     

```{r fig.alt = 'Alt Text Here'}
#b)

```

c. In the Twin Cities plot, play with the zoom number. What does it do?  (just describe what it does - don't actually include more than one map).     

> ANSWER:

d. Try a couple different map types (see `get_stamenmap()` in help and look at `maptype`). Include a map with one of the other map types.    

```{r fig.alt = 'Alt Text Here'}
#d)

```

e. Add a point to the map that indicates Macalester College and label it appropriately. There are many ways you can do this, but it may be easiest with the `annotate()` function (see `ggplot2` cheatsheet).

```{r fig.alt = 'Alt Text Here'}
#e)

```

## Density Plots



## Choropleths {-}


```{r}
# Create a new Starbucks dataset that
# - filters to the US
# - summarizes the number of Starbucks in each state
# - has full names of states in lowercase letters (to match to states_map data created next)

starbucks_us_by_state <- Starbucks %>%
  filter(Country == "US") %>%
  count(`State/Province`) %>%
  mutate(state_name = str_to_lower(abbr2state(`State/Province`)))

# US states map information - coordinates used to draw borders
states_map <- map_data("state")

# map that colors state by number of Starbucks
starbucks_us_by_state %>%
  ggplot() +
  geom_map(
    map = states_map,
    aes(
      map_id = state_name,
      fill = n
    )
  ) +
  # This assures the map looks decently nice:
  expand_limits(x = states_map$long, y = states_map$lat) +
  theme_map()
```



The example above did not account for population of each state in the map. In the code below, a new variable is created, `starbucks_per_10000`, that gives the number of Starbucks per 10,000 people. It is in the `starbucks_with_2018_pop_est` dataset.


```{r}
census_pop_est_2018 <- read_csv("https://milnel2.github.io/112_spring_2023/data/us_census_2018_state_pop_est.csv") %>%
  separate(state, into = c("dot", "state"), extra = "merge") %>%
  select(-dot) %>%
  mutate(state = str_to_lower(state))
```

```{r}
starbucks_with_2018_pop_est <-
  starbucks_us_by_state %>%
  left_join(census_pop_est_2018,
    by = c("state_name" = "state")
  ) %>%
  mutate(starbucks_per_10000 = (n / est_pop_2018) * 10000)
```

### Practice: Starbucks as Choropleth  {-}

```{exercise}
Create a choropleth state map that shows the number of Starbucks per 10,000 people on a map of the US. Use a new fill color, add points for all Starbucks in the US (except Hawaii and Alaska), add an informative title for the plot, alt text and include a caption that says who created the plot (you!). Make a conclusion about what you observe.   
```

> ANSWER:

```{r, fig.alt = ""}


```







## Dynamic Maps with `leaflet` {-}

[Leaflet](https://leafletjs.com/) is an open-source JavaScript library for creating maps. It can be used outside of R, but we will only discuss using the `leaflet` library in R. 

This library uses a different plotting framework from `ggplot2` although it still has a `tidyverse` feel due to its use of the pipe, `%>%` and the way it adds layers to the plot, just like in `ggplot2`.


### Steps to Create a Map {-}

1. Create a map widget by calling `leaflet()` and telling it the data to use.  
2. Add a base map using `addTiles()` (the default) or `addProviderTiles()`.
3. Add layers to the map by using layer functions (e.g. , `addMarkers()`, `addPolygons()`) to modify the map widget.   
4. Repeat step 3 as desired.  
5. Print the map widget to display it.

```{r}
#a)
laurens_favorite_stp <- tibble(
  place = c(
    "Macalester College", "Como XC Ski Course",
    "Battle Creek MTB", "Bole Restaurant", "Mattocks Park",
    "Wabasha Street Caves", "Pizza Luce", "Cold Front Ice Cream"
  ),
  long = c(
    -93.1712321, -93.1412692,
    -93.0161888, -93.164269, -93.171057,
    -93.0891307, -93.1524256, -93.156652
  ),
  lat = c(
    44.9378965, 44.9823411, 44.9383672,
    44.9433359, 44.9817106, 44.9357781,
    44.9468848, 44.9266768
  )
)

```


### Practice: Favorite Places {-}

```{exercise}
In this exercise, you are going to create a single map of some of your favorite places! The end result will be one map.
```

a. Create a data set using the `tibble()` function that has 5 rows of your favorite places. The columns will be the name of the location, the latitude, the longitude, and a column that indicates if it is in your top 3 favorite locations or not. For an example of how to use `tibble()`, look at the `favorite_stp` that is created manually online.  

```{r}
#a)


```

b. Create a map that uses circles to indicate your favorite places. Label them with the name of the place. Choose the base map you like best. Color your 3 favorite places differently than the ones that are not in your top 3. Add a legend that explains what the colors mean. 

```{r fig.alt = 'Alt Text Here'}
#b)

```

