Skip to content

Instantly share code, notes, and snippets.

@mrcaseb
Created February 15, 2022 16:31
Show Gist options
  • Save mrcaseb/4ae605ea5d8c34be712f2ecaa58cdcec to your computer and use it in GitHub Desktop.
Save mrcaseb/4ae605ea5d8c34be712f2ecaa58cdcec to your computer and use it in GitHub Desktop.
library(tidyverse)
library(nflverse)
#> ── Attaching packages ─────────────────────────────────── nflverse 1.0.1.9000 ──
#> ✓ nflfastR 4.3.0.9008 ✓ nflreadr 1.1.3
#> ✓ nflseedR 1.0.2.9001 ✓ nflplotR 1.0.0.9000
#> ✓ nfl4th 1.0.1.9000
#> ──────────────────────────────────────────────────────────────── Ready to go! ──
options(dplyr.summarise.inform = FALSE)
options(nflreadr.verbose = FALSE)
s <- nflreadr::load_schedules(TRUE)
g <- s |>
nflreadr::clean_homeaway(invert = "result") |>
dplyr::mutate(
spread_line = dplyr::case_when(
location == "home" ~ spread_line,
location == "away" ~ -spread_line,
TRUE ~ NA_real_
),
ats = ifelse(result > spread_line, 1, 0)
) |>
dplyr::group_by(season, team) |>
dplyr::arrange(week) |>
dplyr::mutate(
sb_team = ifelse("SB" %in% game_type, 1, 0),
sb_winner = if_else(sb_team == 1 & last(result) > 0, 1, 0, missing = 0)
) |>
dplyr::filter(!is.na(result)) |>
dplyr::group_by(season, team) |>
dplyr::summarise(
games = dplyr::n(),
sb_team = collapse::fmode(sb_team),
sb_winner = collapse::fmode(sb_winner),
ats_w = collapse::fsum(result > spread_line, na.rm = TRUE),
ats_l = collapse::fsum(result < spread_line, na.rm = TRUE),
ats_t = collapse::fsum(result == spread_line, na.rm = TRUE),
cover = ats_w / (ats_w + ats_l),
ats_p = collapse::fsum(result - spread_line, na.rm = TRUE),
mov = collapse::fsum(result, na.rm = TRUE) / games,
ats_margin = collapse::fmean(result - spread_line, na.rm = TRUE),
)
chart <- g |> dplyr::filter(sb_team == 1)
p <- ggplot(chart, aes(x = cover, y = ats_margin, alpha = ifelse(sb_winner == 1, 0.8, 0.2))) +
nflplotR::geom_nfl_logos(aes(team_abbr = team), width = 0.05) +
ggrepel::geom_text_repel(aes(label = season), hjust = 0, size = 2.5, bg.color = "white", color = "black") +
scale_x_continuous(labels = scales::percent) +
scale_alpha_identity() +
ggthemes::theme_fivethirtyeight(base_size = 11, base_family = "Roboto Condensed") +
labs(
title = tools::toTitleCase("How Super Bowl Participants performed against the vegas point spread"),
subtitle = "Super Bowl losing teams transparently displayed. Numbers include postseason.",
x = "Spread Cover Percentage",
y = tools::toTitleCase("Average Margin against the spread"),
caption = glue::glue("Figure:@mrcaseb | Data:nflverse | {lubridate::today()}")
) +
theme(
plot.title.position = "plot",
axis.title = element_text(),
) +
NULL
p
@mrcaseb
Copy link
Author

mrcaseb commented Feb 15, 2022

Output
sb_teams_ats

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment