library(tidyverse)
library(nbastatR)
library(ggtext)
game_logs <- game_logs(
  seasons = c(1978:2020),
  league = "NBA",
  season_types = "Regular Season",
  nest_data = FALSE,
  result_types = "team"
  )
game_logs <- game_logs %>% 
  select(nameTeam, yearSeason, numberGameTeamSeason, fg3aTeam) %>% 
  drop_na(fg3aTeam)

game_logs <- game_logs %>% 
  filter(yearSeason >= 1986) %>% 
  group_by(nameTeam, yearSeason) %>% 
  summarise(fg3aTeam = sum(fg3aTeam),
            games = n()) %>% 
  ungroup()

game_logs <- game_logs %>% 
  mutate(ave_3s = fg3aTeam / games) %>% 
  mutate(rockets = ifelse(nameTeam == "Houston Rockets", "HR", "Other"))
ggplot(game_logs, aes(x = yearSeason, y = ave_3s)) +
  geom_col(data = filter(game_logs, rockets == "HR"), fill = "#CE1141") +
  geom_point(data = filter(game_logs, rockets == "Other"), 
             color = "gray65", alpha = .5) +
  geom_smooth(data = filter(game_logs, rockets == "Other"), 
              color = "gray65", alpha = .3) +
  theme_minimal() +
  labs(x = "NBA Season",
       y = "3-Point Attempts Per Game",
       title = "The <b style='color:#CE1141'>Houston Rockets</b>
       versus <b style='color:gray65'>All Other Teams</b>", 
       subtitle = "The 2019 <b style='color:#CE1141'>Rockets</b> were the first team to attempt 45 3s per game. Will they get to 50?",
       caption = "As of January 5, 2020") +
  theme(plot.title = element_markdown(lineheight = 1.0, face = "bold"),
        plot.subtitle = element_markdown(lineheight = 1.0, face = "bold")) +
  annotate("text", x = 2008, y = 34, label = "James Harden traded\nto the Rockets in 2013", size = 3, color = "#CE1141") +
  annotate("text", x = 2013, y = 42, 
           label = paste0("Steph Curry's 2016\n",
                          "Warriors are the\n",
                          "only team to attempt more\n",
                          "3s than the\n",
                            "Rockets since 2014"),
           size = 3, color = "#1D428A") +
  geom_curve(
    aes(x = 2011.5, y = 32, xend = 2012.5, yend = 29.5),
    curvature = -.5,
    color = "#CE1141",
    arrow = arrow(length = unit(0.03, "npc"))) +
  geom_curve(
    aes(x = 2015, y = 36, xend = 2016, yend = 33),
    curvature = -.5,
    color = "#1D428A",
    arrow = arrow(length = unit(0.03, "npc")))
## `geom_smooth()` using method = 'loess' and formula 'y ~ x'