---
title: "Zillow Map"
subtitle: "Coloring Counties with Data"
theme: flatly 
date: today
toc: true
format:
  html: 
    code-overflow: wrap
    toc: true
    toc-title: "Contents"
    # hide code?

execute:
  warning: false
  message: false
---

# Load Zillow Data

On the [Zillow Data page](https://www.zillow.com/research/data/), one can download ZHVI data for each county in the US.  Data for 2025 was saved in the `week9` folder.  Import below:

```{r, load}
library(tidyverse)
# load housing data for each county
zil <- read_csv("https://euclid.nmu.edu/~joshthom/teaching/dat309/week9/County_zhvi_uc_sfrcondo_tier_0.33_0.67_sm_sa_month_2025.csv")

# clean names
zil <- janitor::clean_names(zil)
```

Next we use the pivoting script created previously to tidy the data 

# Pivot the data
```{r, pivot}
# one could use rowwise(), c_across(), etc but this is nicer
# 
# edit the path below to your copy of the script
source('~/t/dat309/week8/load_clean_zillow.R')
# this creates a variable named value
zil_pivot <- clean_it(zil, 'value')

zil_pivot |> head()

```

# Create a county fips code
The `plot_usmap()` function requires the fips code for plotting.  The alternative is to use lat/lon pairs together with `geom_polygon()`.

The zillow data comes with a state fips code and a municipal fips code we glue together to define a county fips code.

```{r, fips}
# still need to make a county fips code
zil_pivot <- mutate(
  zil_pivot,
  fips = as.character(
    paste0(
      state_code_fips, 
      municipal_code_fips)
  )) |> relocate(fips)
```

# Join Zillow data with Fips data
The `us_map()` function creates a variable called `geom` used to plot a polygon representing each county.

Join the geometry data with the zillow data using the fips code.

```{r, join}
library(usmap)
county_map_data = us_map(regions = 'counties')
cd <- inner_join(zil_pivot, county_map_data)
```

Find the mean home value for each county.

```{r, summarize}
# summary
zil_p <- cd |> 
    group_by(region_name, state_name, fips, geom) |> 
    summarize(mean = mean(value, na.rm=TRUE)) |>
    arrange(-mean) |> ungroup()
```

# Map
```{r, mapping}
library(scales) # for the label_dollar below

# grab coordinates  of center of the counties
# my_spot <- arrange(zil_p, desc(mean)) |> slice_head()
my_spot <- filter(zil_p,
                  str_detect(region_name, "Marquette"),
                  str_detect(state_name,"MI"))

# the geometry object
g <- sf::st_centroid(my_spot$geom)

# extract those coordinates
XY <- attributes(g)$bbox

# data frame to hold the label info
df <- data.frame(
  x = XY[1],
  y = XY[2],
  label = "\u2764") # The Unicode character for a heart
)

plot_usmap(
  data = zil_p, # the joined data
  regions = "counties", 
  values = "mean", # using the mean variable for fill color
  color = "grey90", linewidth = 0.0005) + # make the boundaries small
  labs(title = "Mean Housing Price") + 
  # trans = 'log' plots the colors on a log scale 
  # (good for large scale diffs)
  scale_fill_viridis_c(trans = "log",labels = label_dollar()) +
  # since the values = "mean" is really fill = "mean"
  labs(fill = "Mean Price") +
  # plot a red dot near the most expensive county
  geom_sf(data = my_spot,
    aes(geometry = g), # plot the first centroid
    color = 'red', size = 2) 
#  geom_point(data = df, 
#             mapping = aes_string(x=x,y=y,shape=label),
#             color = 'red', size = 10)
  # geom_image(x=mlon,y=mlat,image="~/dat309/figs/housing.png", size = 5)
```