1. Plot with the Lakers’ Court:
I found this amazing Laker’s home court image and decided to use it for plots Lakers’ Court
There is a lot of things can be done for exploratory analysis with this data set, and I’m really excited about it as a long-term Kobe fan. First let’s load the data up.
library(ggplot2)
library(data.table)
df <- read.csv('data.csv')
df <- setDT(df)
# exclude team_id, team_name, etc.
df[, team_id := NULL]
df[, game_id := NULL]
df[, game_event_id := NULL]
df[, team_name := NULL]
df[, shot_made_flag:= as.factor(shot_made_flag)]
# parse out home vs. away
df[matchup %like% "@", matchup := 'Away']
df[matchup %like% "vs.", matchup := 'Home']
df[, season_num := as.numeric(season)]
# set game_date into data format
df[, game_date:= as.Date(game_date)]
#split into train & test data
train <- df[!is.na(shot_made_flag), ]
test <- df[is.na(shot_made_flag), ]
# split into regular season and playoffs
regular <- train[playoffs == 0]
playoffs <- train[playoffs == 1]
# load basketball court
library(jpeg)
library(grid)
courtimg <- readJPEG('lakers.jpg')
courtimg <- rasterGrob(courtimg, width=unit(1,"npc"), height=unit(1,"npc"))
A function to plot kobe’s shots on the court, I’ve adjusted the image to line-up with the image, though it is still a little bit off.
# base plot function
plot_kobe <- function(data, cat, alpha = 1){
p <- ggplot(data, aes(data[, loc_x], data[, loc_y], color = data[[cat]]))+
annotation_custom(courtimg, -300, 300, -115, 900)+
geom_point(alpha = alpha)+
theme_bw()+
ylim(-80, 400)+
xlim(-280, 280)+
xlab('X')+
ylab('Y')+
scale_color_manual('Shots', values = c('#e61919', '#009999'))
return(p)
}
Let’s first get an impression of all Kobe’s jump shots. He loved to shoot at 45 degrees on both sides of the court, beyond the 3-point line as well as in the middle range.
ggplot(train[action_type == 'Jump Shot'], aes(color = shot_made_flag)) +
annotation_custom(courtimg, -300, 300, -115, 900)+
stat_density2d(geom = 'polygon', contour = T, n = 500, aes(x = loc_x, y = loc_y,
fill = ..level.., alpha = ..level..))+
theme_bw()+
ylim(-80, 400)+
xlim(-280, 280)+
xlab('X')+
ylab('Y')+
scale_fill_gradient('Density', low = '#b3d1ff', high = '#003d99')+
scale_color_manual('Shots', values = c('#ff0000', '#00ffcc'))+
facet_wrap(~shot_made_flag)

So, how deadly is Black Mamba? Here is a plot of Kobe’s shots in the fourth quarter with less than 24 seconds left (last attack chance)
plot_kobe(train[minutes_remaining <= 1 & period == 4 & seconds_remaining <= 24],
cat = 'shot_made_flag')

Kobe’s two points shooting percentage in last 24 seconds of a game:
shoot_percentage(train[minutes_remaining <= 1 & period == 4 & seconds_remaining <= 24], 2)
## [1] 0.4752747
# at home:
shoot_percentage(train[minutes_remaining <= 1 & period == 4 & seconds_remaining <= 24
& matchup == "Home"], 2)
## [1] 0.4720497
# Away
shoot_percentage(train[minutes_remaining <= 1 & period == 4 & seconds_remaining <= 24
& matchup == "Away"], 2)
## [1] 0.4778325