Introduction

This is just the supplementary code to the results in the EDA slide presentation. Just to show how I generated the graphs.


Loading in the data

I load in my dataset and make all the necessary mutations.

important note: As of June 17 2021, the dataset was increased by 1 game thus changing the results slightly from when I created my slides. At the bottom of my code block I loaded in the version of the dataset I worked with.

library(wehoop)
library(tidyverse)
library(lubridate)
library(ggdendro)
library(protoclust)
## Preparing the data ----------------


wnba_pbp_data <- load_wnba_pbp(2021)

# Get the shots and clean this data a bit:
wnba_shots_data <- wnba_pbp_data %>%
  filter(shooting_play)
# Remove unnecessary columns:
wnba_shots_data <- wnba_shots_data %>%
  dplyr::select(-shooting_play, -id, -participants_2_athlete_id,
                -type_abbreviation, -season, -season_type, 
                -home_team_spread, -game_spread, -home_favorite)

# write.csv(wnba_shots_data,'WNBA_shot_data.csv')
## Loading the data for a single game ----------------

wsd <-wnba_shots_data

wsd <- wsd %>% 
  filter(coordinate_x > 0 & coordinate_y > 0) %>% 
  mutate(coordinate_x = coordinate_x - 25) %>% 
  mutate(distance = sqrt((coordinate_x)^2 + coordinate_y^2)) %>% 
  mutate(theta = acos(coordinate_x / distance) * (180 / pi)) %>% 
  mutate(sequence_number = as.integer(sequence_number)) %>% 
  mutate(seconds_elapsed_game = 600 - (as.integer(clock_minutes) * 60 + as.integer(clock_seconds))) %>% 
  mutate(seconds_with_period = (period_number - 1) * 10 * 60 + seconds_elapsed_game) %>% 
  mutate(time_corrected = seconds_to_period(seconds_with_period)) %>% 
  filter(period_number < 5 & distance < 40) ## removed overtime and outlier distances

## loading in the version of wsd that I worked with before the WNBA dataset was increased
wsd <- readRDS("data/wsdHclust.rds")

Getting the Accuracy over X-feet bins from the hoop

The code below gets the shot accuracy for each team binned by every x feet from the hoop.

## these are variable and can be changed, I've only experimented with
## bucket_length being integer values though.
bucket_length = 2
max_bucket = 40
min_thresh = 2 ## min number of shots in order for that bucket to be considered

wsd$cutDist <-cut(wsd$distance, breaks = seq(0, max_bucket, by = bucket_length))
num_buckets = length(unique(wsd$cutDist))

distance_percent_df <- data.frame()
team_list = unique(wsd$team_id)

## loop through each team
for (curr_team_id in team_list){
  print(paste("=> current teamid: ", curr_team_id))

  ## initialize empty vector
  score_percentage = c()
  for (i in seq(length(levels(wsd$cutDist)))) {
    
  
    bucket <- levels(wsd$cutDist)[i]
    
    curr <- wsd %>% 
      filter(cutDist == bucket & team_id == curr_team_id)
    
    curr_team_abbrv <- filter(wsd, home_team_id == curr_team_id)$home_team_abbrev[1]
    
    ## minimum threshhold based on what the user wants
    if(nrow(curr) > min_thresh){
        hit_count <- nrow(filter(curr, scoring_play == TRUE))
        miss_count <- nrow(filter(curr, scoring_play == FALSE))
        percentage <- hit_count / (hit_count + miss_count)
        # print(percentage)
        score_percentage[i] <- percentage
    } else {
        score_percentage[i] <- 0.0
    }
  }
  currdf <- data.frame("Bucket" = levels(wsd$cutDist), "percent" = score_percentage, "team_id" = curr_team_abbrv, "idx" = seq(1, length(score_percentage)))
  distance_percent_df <- rbind(distance_percent_df, currdf)
}
## [1] "=> current teamid:  5"
## [1] "=> current teamid:  9"
## [1] "=> current teamid:  18"
## [1] "=> current teamid:  20"
## [1] "=> current teamid:  8"
## [1] "=> current teamid:  11"
## [1] "=> current teamid:  6"
## [1] "=> current teamid:  3"
## [1] "=> current teamid:  16"
## [1] "=> current teamid:  19"
## [1] "=> current teamid:  17"
## [1] "=> current teamid:  14"
distance_percent_df %>% 
  ggplot() + 
  geom_line(aes(x = idx, y = percent, color = team_id)) +
  labs(title = "Binned Shooting Percentage for each team binned per distance", x = "Feet from Hoop", y = "Shooting Percentage")

Weighted Bins

Since we’re using weighted-euclidean distance, we decided to weight the bins that have more shots higher, the code below finds this.

## bin weights based on the number of shots that were made
bin_weights = c()
total_made_shots <- nrow(filter(wsd , scoring_play == TRUE))

for (i in seq(length(levels(wsd$cutDist)))) {
  # i <- 2
  bucket <- levels(wsd$cutDist)[i]
  # print(bucket)
  curr <- wsd %>% 
    filter(cutDist == bucket & scoring_play == TRUE)
  
  percentage_bucket <- nrow(curr) / total_made_shots
  
  bin_weights[i] <- percentage_bucket
}

plot(bin_weights)


Pairwise distance function

The code below uses the calculated bin_weights to calculate the distance between game-trajectory 1 and game-trajectory 2

## pairwise distance function ----

calc_traj_pairwise <- function(df, bin_weights ,team_id1, team_id2){
  
  num_bins = length(unique(df$idx))
  total_distance <- 0
  
  #pairwise distance between each datapoint and adding them together
  for(i in seq(num_bins)){
    team1_d <- df %>% 
      filter(team_id == team_id1 & idx == i)
    
    team2_d <- df %>% 
      filter(team_id == team_id2 & idx == i)
    
    bin_euc_distance <- bin_weights[i] * (team1_d$percent - team2_d$percent)^2 ## bin_weight
    
    total_distance = total_distance + bin_euc_distance
  }
  total_distance = sqrt(total_distance)
  
  return (total_distance)
}

Distance Matrix and Hierarchical Clustering

team_abbrv_list <- unique(wsd$away_team_abbrev)

team_pairwise_dist <- map_dfr(team_abbrv_list, 
        function(team1){
          map_dfr(team_abbrv_list, 
                  function(team2){
                    tibble("team1" = team1, "team2" = team2, 
                           "distance" = calc_traj_pairwise(distance_percent_df, bin_weights, team1, team2))
          })
        }
      )

## pivot wider
dist_wider <- pivot_wider(team_pairwise_dist, names_from = team2, values_from = distance)

## removing the first label column called team1, then setting it into a matrix
dist_matrix <- dist_wider %>% 
  dplyr::select(-team1) %>% 
  as.matrix()

## setting the row names to be the abbrv list, which is the same order as before
rownames(dist_matrix) <- team_abbrv_list

## creating a distance object out of it
team_dist <- as.dist(dist_matrix)

If I’m honest it seems like new york somehow migrated since the last time I made this dataset but everything is the same. I increased clusters from 3 to 4 to see the same cluster lines as before.

# team_hclust <- hclust(team_dist, method = "complete")

team_hclust <- protoclust(team_dist)
## we can take a quick look at the dendrogram and see the different teams
plot(team_hclust)

## assign the lookup table based on how many clusters we want
team_cluster_lookup <- tibble(team_names = team_abbrv_list , team_cluster = as.factor(cutree(team_hclust, k = 4)))

## annotating the original distance_percent_df with the clusters assigned
annotated_distance_percent_df <- distance_percent_df %>% 
  left_join(team_cluster_lookup, by = c("team_id" = "team_names"))

## graph the clusters
annotated_distance_percent_df %>% 
  ggplot() + 
  geom_line(aes(x = idx, y = percent, color = team_id, group = team_id)) +
  # scale_x_continuous(breaks = seq(0, )) +
  facet_wrap(~team_cluster, ncol=2) +
  labs(title = "Binned Shooting Percentage for each team binned per distance", x = "Feet from Hoop", y = "Shooting Percentage")

Calculating a defense metric for each team

Adding a team_abbrv column to make my life easier.

So what the defensive metric is, is really just how much a current team lowers another team’s shooting accuracy compared to that other team’s usual shooting accuracy.

An example would be if we focus on the SEA team, they play against LV, MIN and IND.

For each bucket of 2 feet, for each game with SEA v other team, I calculate the shooting accuracy and compare it with the overall one, then I summ it together and average it.

\[def_x(team) = \frac{\sum (OppAvgAcc_x - OppCurrAcc_x) }{NumOpp}\] x is the current bucket (e.g bucket 2 are the shots 2 feet to 4 feet from the hoop)

OppAvgAcc is the opponent’s average shot accuracy in bin x

OppCurrAcc is the opponent’s current shot accuracy in the game against the team of interest

NumOpp is the number of opponents that the team of interest plays against

That’s the main idea.

num_buckets = length(unique(wsd$cutDist))

wsd <- wsd %>% 
  mutate(team_id = as.factor(team_id))

team_abbrv_lookup <- unique(dplyr::select(wsd, home_team_id, home_team_abbrev)) %>% 
  rename(team_id=home_team_id, team_abbrv = home_team_abbrev) %>% 
  mutate(team_id = as.factor(team_id))

wsd <- left_join(wsd, team_abbrv_lookup, by = "team_id")
def_percent_df <- data.frame()
team_list = unique(wsd$team_abbrv)


## for each of the other teams except for this one
for (curr_team in team_list){
  print(paste("=> current teamid: ", curr_team))

  def_percentage = c()
  for (i in seq(length(levels(wsd$cutDist)))) {
    
  

    bucket <- levels(wsd$cutDist)[i]
    
    curr <- wsd %>% 
      filter(cutDist == bucket & team_abbrv != curr_team & (home_team_abbrev == curr_team | away_team_abbrev == curr_team))
    
    ## now to go through each unique opponent and add the difference
    list_opp <- unique(curr$team_abbrv)
    defense_val <- 0
    skip <- 0
    for(opp in list_opp){
      
      opp_avg_score_acc <- nrow(filter(curr, scoring_play == TRUE & team_abbrv == opp)) / nrow(filter(curr, team_abbrv == opp))
      opp_overall_avg_score_acc <- filter(distance_percent_df, Bucket == bucket  & team_id == opp)$percent
      
      if(is.na(opp_overall_avg_score_acc)){
        opp_overall_avg_score_acc <- 0
        skip <- skip + 1
      }
      
      defense_val <- defense_val + (opp_overall_avg_score_acc - opp_avg_score_acc)
    }
    
    defense_val <- defense_val / (length(list_opp) - skip)
    
    if(is.na(defense_val)){
      defense_val <- 0
    }
    
    def_percentage <- c(def_percentage, defense_val)

  }
  currdf <- data.frame("Bucket" = levels(wsd$cutDist), "def_percent" = def_percentage, "team_id" = curr_team, "idx" = seq(1, length(def_percentage)))
  
  def_percent_df <- rbind(def_percent_df, currdf)
}
## [1] "=> current teamid:  IND"
## [1] "=> current teamid:  NY"
## [1] "=> current teamid:  CONN"
## [1] "=> current teamid:  ATL"
## [1] "=> current teamid:  MIN"
## [1] "=> current teamid:  PHX"
## [1] "=> current teamid:  LA"
## [1] "=> current teamid:  DAL"
## [1] "=> current teamid:  WSH"
## [1] "=> current teamid:  CHI"
## [1] "=> current teamid:  LV"
## [1] "=> current teamid:  SEA"
def_percent_df <- filter(def_percent_df, idx < 15)

# def_percent_df <- readRDS("def_percent_df.rds")

def_percent_df %>% 
  ggplot() + 
  geom_line(aes(x = idx, y = def_percent, color = team_id)) +
  labs(title = "Binned Defensive Percentage for each team binned per distance", x = "Bucket Feet from Hoop", y = "Defense_Percentage")

Clustering each team’s defensive metric

I needed to tweak the pairwise function to work with this so I just copied an dpaste the distance pairwise function.

calc_def_traj_pairwise <- function(df, bin_weights ,team_id1, team_id2){
  
  # df <- def_percent_df
  # team_id1 = "IND"
  # team_id2 = "SEA"
  
  num_bins = length(unique(df$idx))
  total_distance <- 0.0
  # print(team_id1)
  #pairwise distance between each datapoint and adding them together
  for(i in seq(num_bins)){
    team1_d <- df %>% 
      filter(team_id == team_id1 & idx == i)
    
    team2_d <- df %>% 
      filter(team_id == team_id2 & idx == i)
    
    bin_euc_distance <- bin_weights[i] * (team1_d$def_percent - team2_d$def_percent)^2 ## bin_weight
    
    total_distance = total_distance + bin_euc_distance
  }
  total_distance = sqrt(total_distance)
  
  # print(total_distance)
  return (total_distance)
}

team_abbrv_list <- unique(wsd$away_team_abbrev)

def_team_pairwise_dist <- map_dfr(team_abbrv_list, 
        function(team1){
          map_dfr(team_abbrv_list, 
                  function(team2){
                    tibble("team1" = team1, "team2" = team2, 
                           "distance" = calc_def_traj_pairwise(def_percent_df, bin_weights, team1, team2))
          })
        }
      )

## pivot wider
dist_wider <- pivot_wider(def_team_pairwise_dist, names_from = team2, values_from = distance)

## removing the first label column called team1, then setting it into a matrix
dist_matrix <- dist_wider %>% 
  dplyr::select(-team1) %>% 
  as.matrix()

## setting the row names to be the abbrv list, which is the same order as before
rownames(dist_matrix) <- team_abbrv_list

## creating a distance object out of it
team_dist <- as.dist(dist_matrix)

## displaying the final distance object we can use for clustering
team_dist
##             IND       CONN        PHX        DAL        CHI         LV
## CONN 0.12304445                                                       
## PHX  0.13933602 0.12778858                                            
## DAL  0.16445797 0.19220905 0.11590730                                 
## CHI  0.09404129 0.10753874 0.12899223 0.14522802                      
## LV   0.16065097 0.18625643 0.10604754 0.08529047 0.14436411           
## NY   0.13109242 0.14878764 0.08696410 0.08788434 0.12977185 0.06878613
## MIN  0.13373695 0.12627770 0.10327456 0.14478507 0.10461519 0.12739582
## SEA  0.13620898 0.16006859 0.10079309 0.09630664 0.11994351 0.07828716
## ATL  0.17324176 0.13546777 0.14706762 0.19653574 0.17317482 0.17522933
## LA   0.15533087 0.16374366 0.11637075 0.11366493 0.13600090 0.11400849
## WSH  0.16269615 0.19635831 0.16872735 0.17294999 0.15818516 0.20136610
##              NY        MIN        SEA        ATL         LA
## CONN                                                       
## PHX                                                        
## DAL                                                        
## CHI                                                        
## LV                                                         
## NY                                                         
## MIN  0.11218679                                            
## SEA  0.06489681 0.11306829                                 
## ATL  0.13733109 0.14106250 0.17204724                      
## LA   0.09218051 0.07799843 0.10786319 0.13860421           
## WSH  0.17854264 0.18579783 0.15094816 0.25037640 0.19091810
# team_hclust <- hclust(team_dist, method = "complete")

team_hclust <- protoclust(team_dist)
## we can take a quick look at the dendrogram and see the different teams
plot(team_hclust)

# saveRDS(team_hclust, "def_team_hclust.rds")


## assign the lookup table based on how many clusters we want
team_cluster_lookup <- tibble(team_names = team_abbrv_list , team_cluster = as.factor(cutree(team_hclust, k = 4)))

## annotating the original distance_percent_df with the clusters assigned
annotated_def_percent_df <- def_percent_df %>% 
  left_join(team_cluster_lookup, by = c("team_id" = "team_names"))


## graph the clusters
annotated_def_percent_df %>% 
  ggplot() + 
  geom_line(aes(x = idx, y = def_percent, color = team_id, group = team_id)) +
  # scale_x_continuous(breaks = seq(0, )) +
  facet_wrap(~team_cluster, ncol=2) +
  labs(title = "Binned Defensive Percentage for each team binned per distance", x = "Feet from Hoop (units of 2)", y = "Defensive Metric")