Lecture 23: NBA Tracking Data

Motivation: Play Animation

In Game 5 of the 2026 NBA Finals, the New York Knicks scored their first points on a Jalen Brunson 3 point shot. Figure 1 shows an animation of the same play in which players are represented as dots (colored according to their team) move aross the plane (representing the court)

Animation in which dots (representing players and the ball) move about the plane (representing the basketball court)
Figure 1: Animation of Knicks possession leading up to a Brunson 3 point shot

We will recreate this figure using recently-released tracking data from the NBA.

Tracking Data in the NBA

NBA teams have used cameras to collect player tracking data during games since the 2009-10 regular season. Initially, the league used SportVU, a system of six cameras and proprietary computer vision software initially developed for soccer. In 2013, the league announced a partnership with STATS, LLC to deploy SportVU in all arenas and collect & distribute the data league-wide. That partnership was renewed for the 2016-17 season before the league switched to a different vendor (Second Spectrum) for its optical tracking data. Before the 2023-24 regular season, the NBA announced a new partnership with Sony’s Hawk-Eye Innovations to deploy Hawk-Eye’s 3D optical tracking system in all arenas.

Unlike the NFL, the NBA has been extremely reluctant to release any of its tracking data to the public. Much of the public research1 based on these data has been done by groups who received special access. Despite the lack of formal data releases, some NBA tracking data has still made it to the public domain.

During the 2014-15 regular season, the NBA added a feature to its website in which fans could watch video clips of individual players’ shots and visualize the player & ball movements as dots moving around the court. Neil Johnson found the data underpinning this functionality, scraped it, and shared all that data publicly on GitHub 2. In total, he got 632 games worth of data before the data were taken offline (and the NBA removed the tracking data visualization functionality from its website)3. Since the data were publicly posted, many people have developed code for processing, analyzing, and visualizing these data. I recommend this repository from Rajiv Shah if you want to play around with the older tracking data.

For the better part of a decade, these 632 games from the 2015-16 regular season were the only publicly available NBA tracking data until recently. In October 2026, the NBA announced several new features to its app including Game Pulse which, to quote the NBA’s press release “combines live court visualization… in a live-updating experience.” In other words, the dots on the court had returned and Neil Johnson once again found the underlying data, scraped it, and posted it publicly4.

We will work with a portion of these data to create an animation of a single possession from Game 5 of the 2026 NBA Finals.

Getting Started with Tracking Data

The full data archive (which is about 5GB in size) contains several files and a large directory containing the tracking data. That directory contains sub-directories (one for each day) and each day’s directory contains sub-directories (one for each game). The games are uniquely indexed by a 10-digit numeric id. For instance, the ID for Game 5 of the 2026 Finals is 0042500405.

Each game’s directory contains several JSON files5. Player-tracking data is incredibly structured: player coordinates are nested within frames and frames are nested within games. This makes JSON particularly well-suited for storing tracking data.

NoteInstalling jsonlite

To work with data stored in JSON format, you will need to install the jsonlite package using the code install.packages("jsonlite")

We will start by exploring the data contained in the file metadata.json. Note that R will usually read JSON files in as large named list.

metadata <- jsonlite::fromJSON("metadata.json")
class(metadata)
[1] "list"
names(metadata)
 [1] "schema_version"         "game_id"                "game_date"             
 [4] "game"                   "program"                "archived_at_utc"       
 [7] "coordinate_system"      "players"                "court_direction_events"
[10] "tracking_sha256"        "tracking_bytes"         "coverage_file"         
[13] "tracking_file"         

Many of the attributes in the game’s metadata are self-explanatory (e.g., game_id and game_data). It turns out the game element is itself a list and contains loads of information including the identities of the teams and players involved in the game.

names(metadata$game)
 [1] "gameId"           "gameCode"         "gameStatus"       "gameStatusText"  
 [5] "gameSequence"     "gameDateEst"      "gameTimeEst"      "gameDateTimeEst" 
 [9] "gameDateUTC"      "gameTimeUTC"      "gameDateTimeUTC"  "awayTeamTime"    
[13] "homeTeamTime"     "day"              "monthNum"         "weekNumber"      
[17] "weekName"         "ifNecessary"      "seriesGameNumber" "gameLabel"       
[21] "gameSubLabel"     "seriesText"       "arenaName"        "arenaState"      
[25] "arenaCity"        "postponedStatus"  "branchLink"       "gameSubtype"     
[29] "isNeutral"        "broadcasters"     "homeTeam"         "awayTeam"        
[33] "pointsLeaders"    "_game_date"       "_phase"          

For our purposes, it will be useful to get the identities of the teams and players.

homeID <- metadata$game$homeTeam$teamId
awayID <- metadata$game$awayTeam$teamId

We will also build a data frame containing player name, jersey number, team, and numeric id.

n_players <- length(metadata$players)

player_df <- data.frame(name = rep(NA, times = n_players), 
                        personID = rep(NA, times = n_players),
                        teamID = rep(NA, times = n_players),
                        jersey = rep(NA, times = n_players))
for(i in 1:n_players){
  player_df$name[i] <- metadata$players[[i]]$name
  player_df$personID[i] <- metadata$players[[i]]$personId
  player_df$teamID[i] <- metadata$players[[i]]$team_id
  player_df$jersey[i] <- metadata$players[[i]]$jerseyNum
}

set.seed(441)
player_df |> dplyr::slice_sample(n=5)
           name personID     teamID jersey
1 Carter Bryant  1642868 1610612759     11
2     Josh Hart  1628404 1610612752      3
3  Kelly Olynyk   203482 1610612759      8
4 Devin Vassell  1630170 1610612759     24
5  Dylan Harper  1642844 1610612759      2

The tracking data itself is stored in JSON Lines format6, which requires slightly different syntax to load into R.

connection <- gzfile("tracking.jsonl.gz") 
raw_data <- jsonlite::stream_in(connection)
opening gzfile input connection.

 Found 500 records...
 Found 1000 records...
 Found 1500 records...
 Found 2000 records...
 Found 2500 records...
 Found 3000 records...
 Found 3500 records...
 Found 4000 records...
 Found 4500 records...
 Found 5000 records...
 Found 5500 records...
 Found 6000 records...
 Found 6500 records...
 Found 7000 records...
 Found 7500 records...
 Found 8000 records...
 Found 8500 records...
 Found 9000 records...
 Found 9500 records...
 Found 10000 records...
 Found 10500 records...
 Found 11000 records...
 Found 11500 records...
 Found 12000 records...
 Found 12500 records...
 Found 13000 records...
 Found 13500 records...
 Found 14000 records...
 Found 14500 records...
 Found 15000 records...
 Found 15500 records...
 Found 16000 records...
 Found 16500 records...
 Found 17000 records...
 Found 17500 records...
 Found 18000 records...
 Found 18500 records...
 Found 19000 records...
 Found 19500 records...
 Found 20000 records...
 Found 20500 records...
 Found 21000 records...
 Found 21500 records...
 Found 22000 records...
 Found 22500 records...
 Found 23000 records...
 Found 23500 records...
 Found 24000 records...
 Found 24500 records...
 Found 25000 records...
 Found 25500 records...
 Found 26000 records...
 Found 26500 records...
 Found 27000 records...
 Found 27500 records...
 Found 28000 records...
 Found 28500 records...
 Found 29000 records...
 Found 29500 records...
 Found 30000 records...
 Found 30500 records...
 Found 31000 records...
 Found 31500 records...
 Found 32000 records...
 Found 32500 records...
 Found 33000 records...
 Found 33500 records...
 Found 34000 records...
 Found 34500 records...
 Found 35000 records...
 Found 35500 records...
 Found 36000 records...
 Found 36500 records...
 Found 37000 records...
 Found 37500 records...
 Found 38000 records...
 Found 38500 records...
 Found 39000 records...
 Found 39500 records...
 Found 40000 records...
 Found 40482 records...
 Imported 40482 records. Simplifying...
closing gzfile input connection.

In total, the tracking data file contains nrow(raw_data) lines, with each line representing a single frame, and several different “columns”7

names(raw_data)
 [1] "schema_version" "game_id"        "timestamp_ms"   "timestamp_utc" 
 [5] "units"          "period"         "phase"          "game_clock_ms" 
 [9] "shot_clock_ms"  "home_players"   "away_players"   "other_players" 
[13] "ball"           "on_court"       "last_touch"     "quality"       
[17] "source"        

The variables timestampe_ms and timestamp_utc record the timestamp for each frame. It turns out that during game play (i.e., when period is not NA), the frames are sampled approximately every 200 milliseconds. The gaps are due to a combination of missing tracking data and stoppage periods.

qtr1 <- raw_data |> dplyr::filter(period == 1)
summary(diff(qtr1$timestamp_ms))
1
Get all the frames from the 1st quarter
   Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
  200.0   200.0   200.0   248.7   200.0  1833.0 

The quality element returns a data frame with information about the players on the court. Importantly, it tracks the

set.seed(441)
raw_data$quality |> dplyr::slice_sample(n = 10)
   observed_players
1                 8
2                10
3                 9
4                10
5                 7
6                10
7                 0
8                11
9                 5
10               11
                                                                missing_on_court_player_ids
1                                                                          1628384, 1641705
2                                                                                          
3                                                                                   1628368
4                                                                          1630631, 1642844
5                                                        1628368, 1628973, 1629011, 1641705
6                                                                                          
7  1626157, 1628384, 1628404, 1628969, 1628973, 1630170, 1630577, 1641705, 1642264, 1642844
8                                                                                          
9                                               1628368, 1628973, 1629013, 1630170, 1641705
10                                                                                         
   lineup_known all_ten_and_ball_observed source_interpolated
1          TRUE                     FALSE               FALSE
2          TRUE                      TRUE               FALSE
3          TRUE                     FALSE               FALSE
4          TRUE                     FALSE               FALSE
5          TRUE                     FALSE               FALSE
6          TRUE                      TRUE               FALSE
7          TRUE                     FALSE               FALSE
8          TRUE                      TRUE               FALSE
9          TRUE                     FALSE               FALSE
10         TRUE                      TRUE               FALSE
   clock_interpolated
1               FALSE
2                TRUE
3               FALSE
4                TRUE
5               FALSE
6                TRUE
7               FALSE
8                TRUE
9               FALSE
10               TRUE

We can tabulate the number of players whose locations are recorded in every frame

table(raw_data$quality$observed_players)

    0     1     2     3     4     5     6     7     8     9    10    11    12 
 8792   456   668   859  1130  1476  1886  2408  3669  5678 10051  2548   670 
   13    14    15 
  163    24     4 

We see that there are some frames with no player locations recorded and other frames with 10 players. For simplicity, we will focus only on the frames with at least one and no more than 10 player locations recorded.

tracking_data <-
  raw_data |>
  dplyr::filter(quality$observed_players %in% 1:10 & !is.na(period))
table(tracking_data$period)

   1    2    3    4 
6042 6532 8183 7522 

In each frame (i.e., line/row in tracking_data), the player and ball locations are saved in home_players, away_players, and ball. These are saved as individual data frames. For instance, here are the home team locations at a single frame

tracking_data$home_players[[1470]]
  player_id    team_id                            xyz on_court
1   1628368 1610612759 35.290250, 21.272083, 2.976417     TRUE
2   1630170 1610612759 24.583333, -1.305083, 3.044583     TRUE
3   1630577 1610612759  22.800167, 8.062417, 2.712417     TRUE
4   1641705 1610612759 38.130500, 20.077083, 3.721083     TRUE
5   1642264 1610612759 37.359333, -2.545333, 3.264917     TRUE

The “column” xyz contains the x, y, and z coordinate of the player.

tracking_data$home_players[[1470]]$xyz[[1]]
[1] 35.290250 21.272083  2.976417

The following codeblock builds a data table where each row is a frame-player combination. It will contain all available tracking data in a long format

positions <- list()
for(i in 1:nrow(tracking_data)){
  tmp_players <- 
    tracking_data$home_players[[i]] |>
    dplyr::bind_rows(tracking_data$away_players[[i]]) |>
    dplyr::rowwise() |>
    dplyr::mutate(x = unlist(xyz)[1], y = unlist(xyz)[2], z = unlist(xyz)[3]) |>
    dplyr::ungroup() |>
    dplyr::select(-xyz)
  
  if(!is.null(tracking_data$ball$xyz[[i]])){
    tmp_ball <-
      data.frame(
        player_id = 0L,
        team_id = 0L, 
        on_court = TRUE, 
        x = tracking_data$ball$xyz[[i]][1],
        y = tracking_data$ball$xyz[[i]][2],
        z = tracking_data$ball$xyz[[i]][3])
  } else{
    tmp_ball <-
      data.frame(
        player_id = 0L, 
        team_id = 0L, 
        on_court = TRUE, 
        x = NA,
        y = NA,
        z = NA)
  }
  
  
  
  positions[[i]] <-
    dplyr::bind_rows(tmp_players, tmp_ball) |>
    dplyr::mutate(
      frame = i,
      game_clock_ms = tracking_data$game_clock_ms[i],
      period = tracking_data$period[i],
      timestamp_ms = tracking_data$timestamp_ms[i],
      timestamp_utc = tracking_data$timestamp_utc[i])
  
  
}

positions_df <-
  dplyr::bind_rows(positions) |>
  dplyr::left_join(
    y = player_df |> dplyr::rename(player_id = personID) |> dplyr::select(player_id, name, jersey))
1
We will loop over every frame in tracking_data and save the player & ball coordinates in a data table. We will temporarily save these frame-level tables in a list and then concatenate them all at the very end.
2
Create a single table with all home and away players
3
Extracts the individual coordinates into three separate columns
4
Removes the xyz variable, which stored coordinates in a single vector
5
If we have available ball coordinates, we’ll save those too
6
So that we can put ball and player coordinates in a single table, we’ll give the ball a player_id and team_id of 0L. The L records this as an integer and not a double
7
Combine the player & ball data and add columns recording the frame number, game clock and timestamps
8
Concatenate across frames and also join in player names and jersey numbers
Joining with `by = join_by(player_id)`

Animating a Single Play

We will focus on the first made shot by the Knicks in the game — a successful 3 point shot by Jalen Brunson. To do this end, we create a single data frame where the game clock is between 9:48 and 9:28 in the first quarter.

possession <-
  positions_df |>
  dplyr::filter(period == 1 & 
                  game_clock_ms < (9 * 60 + 48) * 1000 & 
                  game_clock_ms >= (9*60 + 28) * 1000) |>
  dplyr::arrange(frame)

We can visualize the entire trajectory of Brunson, one Spurs defender (Stephon Castle), and the ball over the span of these 20 seconds. Importantly, the coordinate system places the origin at mid-court. Regulation NBA courts measures 94 ft by 50 ft so the court coordinates are in the range \([-47,47] \times [-25, 25]\).

brunson_id <- player_df |> dplyr::filter(name == "Jalen Brunson") |> dplyr::pull(personID)
castle_id <- player_df |> dplyr::filter(name == "Stephon Castle") |> dplyr::pull(personID)
brunson <- possession |> dplyr::filter(player_id == brunson_id)
castle <- possession |> dplyr::filter(player_id == castle_id)
ball <- possession |> dplyr::filter(player_id == 0L)

knicks_blue <- "#006bb6"
knicks_orange <- "#f58426"
spurs_black <- "#000000"
spurs_silver <- "#c4ced4"

par(mar = c(3,3,2,1), mgp = c(1.8, 0.5,0))

plot(1, type = "n", xlim = c(-47, 47), ylim = c(-25, 25))
rect(xleft = -47, ybottom = -25, xright = 47, ytop = 25)

points(ball$x, ball$y, col = 'orange', pch = 16, cex = 1)
lines(ball$x, ball$y, col = 'orange')

points(brunson$x, brunson$y, col = knicks_blue, pch = 16, cex = 1.5)
lines(brunson$x, brunson$y, col = knicks_blue)

points(castle$x, castle$y, col = spurs_black, pch = 16, cex = 1.5)
1
You can look up color codes corresponding to each NBA team at nbacolors.com.
2
plot will include a bit of padding beyond the horizontal and vertical limits set by xlim and ylim
3
Draw a rectangle representing the absolute edges of the court.
Figure 2

Adding Court Landmakrs

We can improve the plot above by adding in several court landmarks based on measurements provided in the NBA Rulebook.

Diagram with several circles and lines corresponding to different landmarks of an NBA court along with measurements

NBA Court Dimensions
draw_circle <- function(center = c(0,0), theta_start = 0, theta_end = 2*pi, radius = 1, lwd = 1.5, lty = 1){
  theta_seq <- seq(theta_start, theta_end, length = 1000)
  x <- center[1] + radius*cos(theta_seq)
  y <- center[2] + radius*sin(theta_seq)
  lines(x,y, lwd = lwd, lty = lty)
}

plot_court <- function(){
  
  par(mar = c(1,1,2,1), mgp = c(1.8, 0.5, 0))
  plot(1, type= "n", xlim = c(-55, 55), ylim= c(-30,30), xaxt = "n", yaxt ="n")
  rect(-47, -25, 47, 25, lwd = 3)
  lines(x = c(0,0), y = c(-25,25), lwd = 1.5)
  
  draw_circle(center = c(0,0), radius = 6)
  draw_circle(center = c(0,0), radius = 2)
  
  
  draw_circle(center = c(-47+5.25, 0), radius = 0.75)
  draw_circle(center = c(47 - 5.25, 0), radius = 0.75)
  
  rect(xleft = -47, ybot = -6, xright = -47 + 19, ytop = 6, lwd = 1.5)
  rect(xleft = 47-19, ybot = -6, xright = 47, ytop = 6, lwd = 1.5)
  rect(xleft = -47, ybot = -8, xright = -47+19, ytop = -6, lwd = 1.5)
  rect(xleft = -47, ybot = 6, xright = -47+19, ytop = 8, lwd = 1.5)
  rect(xleft = 47-19, ybot = -8, xright = 47, ytop = -6, lwd = 1.5)
  rect(xleft = 47-19, ybot = 6, xright = 47, ytop = 8, lwd = 1.5)
  
  draw_circle(center = c(47-5.25, 0),
              theta_start = pi/2 + acos(22/23.75), theta_end = 3*pi/2 - acos(22/23.75),
              radius = 23.75)
  draw_circle(center = c(-47+5.25, 0),
              theta_start = 3*pi/2 + acos(22/23.75), theta_end = 2*pi + pi/2 - acos(22/23.75),
              radius = 23.75)
  
  tp_line_length <- sqrt(23.75^2 - 22^2)
  lines(x = c(-47, -47+tp_line_length + 5.25), y = c(22,22))
  lines(x = c(-47, -47+tp_line_length + 5.25), y = c(-22,-22))
  lines(x = c(47-tp_line_length - 5.25, 47), y = c(22,22))
  lines(x = c(47-tp_line_length - 5.25, 47), y = c(-22,-22))
  
  draw_circle(center = c(47-5.25, 0),
              theta_start = pi/2, theta_end = 3*pi/2,
              radius = 4)
  lines(x = c(47-5.25, 47), y = c(-4,-4), lwd = 1.5)
  lines(x = c(47-5.25, 47), y = c(4,4), lwd = 1.5)
  
  draw_circle(center = c(-47+5.25, 0),
              theta_start = 3*pi/2, theta_end = 3*pi/2 + pi,
              radius = 4)
  lines(x = c(-47+5.25, -47), y = c(-4,-4), lwd = 1.5)
  lines(x = c(-47+5.25, -47), y = c(4,4), lwd = 1.5)
  
  lines(x = c(-47+4, -47+4), y = c(-3,3), lwd = 2)
  lines(x = c(47-4, 47-4), y = c(-3,3), lwd = 2)
  
  draw_circle(center = c(-47+19, 0),
              theta_start = 3*pi/2, theta_end = 5*pi/2, radius = 6, lty = 1)
  draw_circle(center = c(-47+19, 0),
              theta_start = pi/2, theta_end = 3*pi/2, radius = 6, lty = 2)
  
  draw_circle(center = c(47-19, 0),
              theta_start = 3*pi/2, theta_end = 5*pi/2, radius = 6, lty = 2)
  draw_circle(center = c(47-19, 0),
              theta_start = pi/2, theta_end = 3*pi/2, radius = 6, lty = 1)
 
}
1
The playable area is 94ft x 50ft but we will set a larger plot range to account for the apron (i.e., the out-of-bounds areas surrounding the court).
2
Boundary of the court
3
Halfline
4
Center of the rim is 5’3” away from the baseline and has a 9” internal radius
5
Box inside the key measures 19’ x 12’ and the whole key measures 19’ x 16’
6
Circular part of the three point arc has a radius of 23’9” and 22” to the corner. With a bit of trigonometry, we can figure out how much of the circular arc to draw
7
Compute how far the three point line extends parallel to the sidelines and perpendicular to baseline. Then add horizontal lines connecting to the arc.
8
The restricted area is formed with a half-circle of radius 4’ from the center of the basket and extends to the baseline.
9
The backboard measures 6’ across and its front edge is positioned 4’ from the baseline
10
The circle at the top of the key measures 6”.

Frame-by-Frame Illustration

To create an animation, we will make a separate image showing all players and the ball in each frame. Then, we can stitch those images together into a GIF. To simplify this process, we define a function in the codeblock that plots the locations in each frame.

plot_frame <- function(frame_number, homeID, awayID, home_col, away_col){
  
  plot_court()
  players <-
    possession |> 
    dplyr::filter(frame == frame_number & player_id != 0L) |>
    dplyr::mutate(
      col = dplyr::case_when(
        team_id == homeID ~ home_col,
        team_id == awayID ~ away_col))
  ball <-
    possession |>
    dplyr::filter(frame == frame_number & player_id == 0L) |>
    dplyr::mutate(col = "orange")
  
  points(players$x, players$y,
         pch = 16, cex = 3,
         col = players$col)
  text(players$x, players$y, labels = players$jersey, cex = 0.75,
       col = "white")
  mtext(frame_number, side = 3)
  
  points(ball$x, ball$y, col = ball$col, pch = 16)
}
1
Call our function to draw the court with all the landmarks

To illustrate, here are the positions of the players in frame number 1450 (approximately halfway through the possession).

plot_frame(frame_number = 1450, homeID = homeID, awayID = awayID, home_col = spurs_black, away_col = knicks_blue)
Figure 3

In order to create an animation, we can plot the player and ball location in each frame and stitch them together into a GIF using ImageMagick. You will first need to download the binary associated with your system from the ImageMagick website and follow the appropriate installation instructions. Then, once you have saved the frame-by-frame images sorted chronologically by frame number in a directory, you can use the command magick to create a GIF. Full documentation for creating such animation is available here. The most salient option to run with magick is delay, which controls the length of the pause between images. Since the NBA data is sampled every 200ms, we will specify the option -delay 20 to match the 5 frames per second rate in the data.

ImportantSubdirectory for Images

In the codeblock below, I set the variable target and use it when calling png. This is the name of a sub-directory that I created within my working directory to hold the frame-by-frame images. If you want to run this code locally, you will need to create a similar sub-directory and update the assignment of target with that sub-directory’s name.

target <- "figures/lecture23/"
for(frame_number in unique(possession$frame)){
  png(paste0(target, "/brunson3pt_", frame_number, ".png"),
      width = 8, height = 4.5, units = "in", res = 400)
  plot_frame(frame_number = frame_number, homeID = homeID, awayID = awayID,
             home_col = spurs_black, away_col = knicks_blue)
  dev.off()
}

Footnotes

  1. For instance, these papers about about quantifying defensive skill and introducing expected possession value.↩︎

  2. Although the latest commit removed most games, you can access the full data from an earlier commit↩︎

  3. You can read more about this project at Neil’s Substack.↩︎

  4. You can read more about how he did so on his Substack.↩︎

  5. JavaScript Object Notation is standard file format that stores data structured as name-value pairs.↩︎

  6. If you want to know more about why JSON and JSON Lines are useful, check out this article from NCBI.↩︎

  7. Rather than viewing the data as a traditional table, it’s better to think of it as a list with each element having the same length (and arranged in the same order)↩︎