---
title: "Load & Wrangle Zillow Data"
subtitle: "Intro loops & functions"
theme: flatly 
date: today
toc: true
format:
  html: 
    code-overflow: wrap
    toc: true
    toc-title: "Contents"
    # hide code?

execute:
  warning: false
  message: false
---

#### Plotting US maps

Today we annotate (ch. 13) us maps and join data (ch. 20).

```{r}
library(readr)
library(tidyverse)
library(usmap)
library(scales)
```

```{r}
# load data
disc <- read_csv("https://euclid.nmu.edu/~joshthom/Teaching/DAT309/w23/Week12/disc_golf_locations.zip")
# compute number of courses per state
disc_state <- disc |> 
  group_by(state) |> 
  summarize(num_courses = n())

# load the population of the US (in 2011)
us <- read_csv("US_Counties.csv")
us <- janitor::clean_names(us)
us_pop <- us |> 
  group_by(state_name) |> 
  summarize(pop = sum(population))

# join the two datasets
disc_sp <- disc_state |> 
  left_join(
    us_pop, 
    by = c("state" = "state_name")) |> 
  glimpse()

# compute the number of courses per million
disc_sp <- disc_sp |> 
  mutate(density = 1000000*num_courses/pop)

# use viridis colors
plot_usmap(data = disc_sp, 
           values = "density", 
           color = "red") + 
  scale_fill_viridis_c(
    labels=label_number()
  ) +
  theme(legend.position = "right") +
  labs(fill = str_wrap("Courses per Million People",width = 10))
```

```{r}
# filter mqt data
mqt <- disc |> filter(city=="Marquette", state == "Michigan")

# transform lat/log into usmap coords
mqt_t <- usmap_transform(
  mqt,
  input_names=c("longitude","latitude"))

# add the id variable (formatted) from mqt to mqt_t
mqt_t <- mqt_t |> 
  mutate(mqt_t, id = str_wrap(mqt$id,width=20))

# make a string of upper midwest states
umw <- c("Michigan","Wisconsin","Minnesota")

# this plots the outline
plot_usmap(include = umw) +
  # here we plot red dots
  geom_point(
    data = usmap_transform(
      filter(disc, state %in% umw),
      input_names=c("longitude","latitude")), 
    # recall, usmap_transform creates variables x and y
    aes(x = x, y = y),
    color = "red", alpha = 0.225) +
  labs(title = "Disc Golf Locations",
       subtitle = "Source: Kaggle/DGPA") +
  theme(legend.position = "right") +
  
  # note how we're using the transformed x,y coords
  annotate(
    # shift the label directly up
    geom = "label", 
    x = mqt_t$x[1], 
    y = mqt_t$y[1]+100000,
    # use the label from mqt
    label = mqt$id[1],
    hjust = "left", 
    color = "black", 
    fill = "grey") + 
  
  annotate(
    geom = "segment",
    # shift the line up and over
    x = mqt_t$x[1], 
    y = mqt_t$y[1], 
    xend = mqt_t$x[1]+100000, 
    yend = mqt_t$y[1]+80000, color = "black",
    arrow = arrow(
      angle = 15,
      ends = "first", 
      type = "closed")
  )
```