library(plotly)
library(dplyr)
library(readr)

#Read in data
countypresidential_election_2000_2020 <- "https://raw.githubusercontent.com/APM3030/STA553/main/data/countypresidential_election_2000-2020.csv"
countypresidential_election_2000_2020 <- read_csv(countypresidential_election_2000_2020)




countypresidential_election_2000_2020$county_name <- tolower(countypresidential_election_2000_2020$county_name)

countypresidential_election_2000_2020$county_name %<>%
  gsub(" county", "", .) %>%
  gsub(" parish", "", .) %>%
  gsub(" ", "", .) %>%
  gsub("[.]", "", .)

countypresidential_election_2020 <- countypresidential_election_2000_2020 %>% filter(year == "2020" , party == "REPUBLICAN" | party == "DEMOCRAT") %>% select(state_po , county_name , county_fips , party , candidatevotes) %>% pivot_wider(names_from = party, values_from = candidatevotes , values_fn = sum)

#Determine the winner of each county

for (i in 1:nrow(countypresidential_election_2020)) {
  if (countypresidential_election_2020$DEMOCRAT[i] > countypresidential_election_2020$REPUBLICAN[i]) {
    countypresidential_election_2020$win[i] = 'Joseph Biden'
  } else {
    countypresidential_election_2020$win[i] = 'Donald Trump'
  }
}
countypresidential_election_2020 <- countypresidential_election_2020 %>% select(county_name , win)

#rename variables
names(countypresidential_election_2020) <- c("subregion" , "win")
#County and State Data 
county_df <- map_data("county")
county_df$subregion <- gsub(" ", "", county_df$subregion)

state_df <- map_data("state")

#join data
choropleth <- inner_join(county_df, countypresidential_election_2020, by = "subregion")
choropleth <- choropleth[!duplicated(choropleth$order), ]


#plot
p <- ggplot(choropleth, aes(long, lat, group = group)) +
  geom_polygon(aes(fill = win), 
               colour = alpha("white", 1/2), size = 0.1)  +
  geom_polygon(data = state_df, colour = "white", fill = NA , size = 0.1) + 
  scale_fill_manual(values = c('red','blue')) +
  ggtitle("2020 US County Election Results") +
  theme_void()

# ggplotly
p <- ggplotly(p, tooltip = 'text') %>% 
  layout(
    hovermode = 'x',
    margin = list(
      t = 30,
      b = 20,
      l = 20,
      r = 20),
    legend = list(
      orientation = 'h',
      x = 0,
      y = 1.05,
      xanchor = 'left')) 
    


p <- style(p, hoverinfo = 'none', traces = c(3))

p