For the following vignette, you’ll need the sportyR
,
ggplot2
, and gganimate
packages loaded into
your workspace.
library(sportyR)
library(ggplot2)
library(gganimate)
If this is your first experience with plotting tracking data, please
check out the plotting-tracking-data vignette.
Otherwise, let’s see how to make GIFs with sportyR
and
gganimate
.
For this example, we’ll use a play from Week 15 of the 2018 NFL season between the Chicago Bears and Green Bay Packers. Data made available for the Big Data Bowl 2021 Kaggle competition.
# Load the play data
<- data.table::fread(
example_nfl_play ::glue(
glue"https://raw.githubusercontent.com/sportsdataverse/sportyR/",
"main/data-raw/example-pbp-data.csv"
)
)
# Convert to data frame
<- as.data.frame(example_nfl_play) example_nfl_play
To keep things easy, let’s specify the colors for each team’s dots on the resulting GIF. We’ll make the Bears orange and the Packers yellow. The football will also need a dot to be seen; let’s make it brown.
# Prep data for plotting
"team"] == "home", "color"] <- "#c83803"
example_nfl_play[example_nfl_play["team"] == "away", "color"] <- "#ffb612"
example_nfl_play[example_nfl_play["team"] == "football", "color"] <- "#624a2e" example_nfl_play[example_nfl_play[
First, let’s draw an NFL field via geom_football("nfl")
.
We’ll adjust the origin to be in the lower left corner of the field, as
per the notes on the coordinate system on the Kaggle page describing the
data.
# Create the field
<- geom_football("nfl", x_trans = 50, y_trans = 26.6667)
nfl_field
# Display the field
nfl_field
Looks good! Now, let’s animate using gganimate
.
# Add the points on the field
<- nfl_field +
play_anim geom_point(
data = example_nfl_play,
aes(x, y),
color = example_nfl_play$color
+
) transition_time(example_nfl_play$frameId)
# Show the animation
play_anim
Easy peasy. As noted on the plotting-tracking-data vignette, this too works so long as the geospatial data is provided and contains a way to identify and order the frames of the resulting GIF.