I need your help!

I want your feedback to make the book better for you and other readers. If you find typos, errors, or places where the text may be improved, please let me know. The best ways to provide feedback are by GitHub or hypothes.is annotations.

Opening an issue or submitting a pull request on GitHub: https://github.com/isaactpetersen/Fantasy-Football-Analytics-Textbook

Hypothesis Adding an annotation using hypothes.is. To add an annotation, select some text and then click the symbol on the pop-up menu. To see the annotations of others, click the symbol in the upper right-hand corner of the page.

5  Data Visualization

5.1 Getting Started

5.1.1 Load Packages

Code
library("nflplotR")
library("plotly")
library("gghighlight")
library("ggridges")
library("tidyverse")

5.1.2 Load Data

Code
load(file = "./data/nfl_pbp.RData")
load(file = "./data/player_stats_weekly.RData")
load(file = "./data/player_stats_seasonal.RData")

We created the player_stats_weekly.RData and player_stats_seasonal.RData objects in Section 4.4.3.

5.2 Overview

5.2.1 Principles of Graphic Design

When designing graphics, it is important to understand general principles of graphic design. An article that describes important principles about graphic design is at the following link: https://www.adobe.com/express/learn/blog/8-basic-design-principles-to-help-you-create-better-graphics (archived at https://perma.cc/29P9-NNSK). The important principles include:

  1. Focus on alignment.
  2. Use hierarchy to help focus your design.
  3. Leverage contrast to accentuate important design elements.
  4. Use repetition to your advantage.
  5. Consider proximity when organizing your graphic elements.
  6. Make sure your designs have balance.
  7. Optimize color to support your design.
  8. Leave negative space.

5.2.2 Principles of Data Visualization

Data visualization involves graphic design in a particular domain—the visualization of data (numeric-derived information). Schwabish (2021) describes five principles in data visualization:

  1. Show the data.
  2. Reduce the clutter.
  3. Integrate the graphics and text.
  4. Avoid the spaghetti chart.
  5. Start with gray.

“Showing the data” involves showing the data that matters the most. “Reducing the clutter” involves removing non-data things that obscure the data—for example, extraneous gridlines, tick marks, data markers (e.g., symbols to distinguish between series), and complex shadings (e.g., textured or filled gradients). “Integrating the graphics and text” involves using headline titles, clear and useful labels (instead of legends), and helpful annotations. Headline or newspaper-like titles are titles that are succinct with active phasing and that indicate the take-away message (e.g., “Quarterbacks Threw Fewer Touchdowns in 2024 than in Previous Years”). In terms of labels, Schwabish (2021) advocates to label the data directly instead of using a legend. In terms of helpful annotations, you can provide additional text that helps explain the data (e.g., peaks or valleys, outliers, or other variations that deserve explanation), including how to interpret the chart. “Avoiding the spaghetti chart” means avoiding packed charts with too much information that makes them difficult to interpret. Spaghetti charts are lines with many lines that, make the plot look like a bunch of spaghetti. However, Schwabish (2021) also advocates against using charts of other types that are complicated and difficult to interpret due to too much information, such as complicated maps or bar plots with too many colors, icons, or bars. If there are too many lines or series, Schwabish (2021) advocates breaking it up into multiple charts (i.e., facets, trellis charts, or small multiples). An example of faceted charts is depicted in Figure 5.25. “Starting with gray” refers to the idea of using gray as the default color for most lines/points/bars, so that you can use a color to highlight the lines/points/bars of interest. In addition, as noted by Schwabish (2021), it is important to treat data as objectively as possible and not to present figures in a biased way as to mislead.

In his classic book, Tufte (2001) states that effective data visualizations should follow principles of graphical excellence and integrity. He notes that “Graphical excellence is that which gives to the viewer the greatest number of ideas in the shortest time with the least ink in the smallest space.” (p. 51). That is, data visualizations should seek to maximize the data-to-ink ratio (within reason), and should spend less space on “fluff” (i.e., non-data things that can be erased without losing meaning, such as grid lines, redundancies, etc.). This is consistent with Schwabish’s -Schwabish (2021) principles of showing the data and reducing the clutter. Tufte (2001) describes six principles of graphical integrity:

  1. The representation of numbers, as physically measured on the surface of the graphic itself, should be directly proportional to the numerical quantities represented.
  2. Clear, detailed, and thorough labeling should be used to defeat graphic distortion and ambiguity. Write out explanations of the data on the graphic itself. Label important events in the data.
  3. Show data variation, not design variation.
  4. In time-series displays of money, deflated and standardized units of monetary measurement are nearly always better than nominal units.
  5. The number of information-carrying (variable) dimensions depicted should not exceed the number of dimensions in the data.
  6. Graphics must not quote data out of context.

— Tufte (2001, p. 77)

Tufte (2001) also provides recommendations for friendly, accessible graphics, including:

  • spell words out (rather than using abbreviations)
  • have words run from left to write (including the y-axis title)
  • include little messages to help explain the data
  • place labels on the graphic so no legend is needed
  • avoid elaborately encoded shadings, cross-hatching, and colors
  • avoid “chartjunk”—i.e., unnecessary or distracting elements (e.g., excessive decoration, overly complex graphics, graphical effects, and irrelevant information such as moiré vibration, heavy grids, and self-promoting graphs) that do not improve viewers’ understanding of the data
  • if colors are used, use colors that are distinguishable by color-deficient and color-blind viewers (red–green is a common form of color-blindness)
  • use type (i.e., of the text) that is clear, precise, and modest
  • use text that is upper-and-lower case, not all capitals

An example figure that applies these principles of data visualization is in Figure 5.1.

Code
confidenceLevel <- .95 # for 95% confidence interval

player_stats_seasonal_offense_summary <- player_stats_seasonal_offense %>%
    filter(position_group %in% c("QB","RB","WR","TE")) %>% 
  group_by(position_group) %>%
  summarise( 
    n = sum(!is.na(fantasy_points)),
    mean = mean(fantasy_points, na.rm = TRUE),
    sd = sd(fantasy_points, na.rm = TRUE)
  ) %>%
  mutate(se = sd/sqrt(n)) %>%
  mutate(
    ci_lower = mean - qt(p = 1 - (1 - confidenceLevel) / 2, df = n - 1) * se,
    ci_upper = mean + qt(p = 1 - (1 - confidenceLevel) / 2, df = n - 1) * se,
    positionLabel = case_match(
      position_group,
      "QB" ~ "Quarterback",
      "RB" ~ "Running Back",
      "WR" ~ "Wide Receiver",
      "TE" ~ "Tight End"
      )
  )

ggplot2::ggplot(
  data = player_stats_seasonal_offense_summary %>%
    filter(position_group %in% c("QB","RB","WR","TE")),
  mapping = aes(
    x = positionLabel,
    y = mean,
    fill = positionLabel
    )
) +
  geom_bar(
    stat = "identity") +
  geom_errorbar(
    aes(
      ymin = ci_lower,
      ymax = ci_upper),
    width = 0.2,
    color = "black"
  ) +
  gghighlight::gghighlight(
    positionLabel == "Quarterback",
    label_key = positionLabel) +
  labs(
    x = "Position",
    y = "Fantasy Points",
    title = "Quarterbacks Score More Fantasy Points than Other Positions"
  ) +
  annotate(
    "segment",
    x = 3.5,
    xend = 3.2,
    y = 70,
    yend = 35,
    color = "blue",
    linewidth = 1.5,
    alpha = 0.6,
    arrow = arrow()) +
  annotate(
    "text",
    x = 2.75,
    y = 75,
    label = "Tight Ends score fewer fantasy\npoints than other positions",
    hjust = 0) + # left-justify
  theme_classic() + 
  theme(legend.position = "none") +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Example Figure that Applies the Principles of Data Visualization.
Figure 5.1: Example Figure that Applies the Principles of Data Visualization.

5.2.3 Creating Data Visualizations in R

The Data Visualization Catalogue provides examples of various types of plots depending on one’s goal: https://datavizcatalogue.com/search.html. The R Graph Gallery provides examples of various types of plots and how to create them in R: https://r-graph-gallery.com. Books on data visualization in R include ggplot2: Elegant Graphics for Data Analysis (Wickham, 2024) and R Graphics Cookbook: Practical Recipes for Visualizing Data (Chang, 2018). In this chapter, we will examine how to create statistical graphics to visualize data. We will create the plots using the ggplot2 package. When creating plots in ggplot2 with multiple points or lines (e.g., multiple players or levels of a predictor variable), it is easiest to do so with the data in long form (as opposed to wide form).

A key principle of graphic design and data visualization is the importance of contrast. Each visual component (e.g., line) that is important to see should be easy to distinguish. For instance, you can highlight lines or points of interest to draw people’s attention to the target of interest (Schwabish, 2021). For examples of highlighting in figures, see Figures 5.21 (Section 5.5.1) and 14.4. It is also important to use color schemes with distinguishable colors. Good color schemes for sequential, diverging, and qualitative (i.e., categorical) data are provided by ColorBrewer (https://colorbrewer2.org) and are available using the scale_color_brewer() and scale_fill_brewer() functions of the ggplot2 package, as demonstrated in Figure 5.24 (Section 5.6.2).

5.3 Univariate Distribution

5.3.1 Histogram

A histogram of fantasy points is depicted in Figure 5.2.

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense %>%
    filter(position_group %in% c("QB","RB","WR","TE")),
  mapping = aes(
    x = fantasy_points)
) +
  geom_histogram(
    color = "#000000",
    fill = "#0099F8"
  ) +
  labs(
    x = "Fantasy Points",
    title = "Histogram of Fantasy Points"
  ) +
  theme_classic() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Histogram of Fantasy Points.
Figure 5.2: Histogram of Fantasy Points.

5.3.2 Density Plot

A histogram of fantasy points is depicted in Figure 5.3.

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense %>%
    filter(position_group %in% c("QB","RB","WR","TE")),
  mapping = aes(
    x = fantasy_points,
    fill = position_group)
) +
  geom_density(alpha = 0.7) + # add transparency
  labs(
    x = "Fantasy Points",
    fill = "Position",
    title = "Density Plot of Fantasy Points by Position"
  ) +
  theme_classic() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Density Plot of Fantasy Points by Position.
Figure 5.3: Density Plot of Fantasy Points by Position.

5.3.3 Histogram with Overlaid Density and Rug Plot

A histogram of fantasy points with an overlaid density and rug plot is depicted in Figure 5.4.

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense %>%
    filter(position_group %in% c("QB","RB","WR","TE")),
  mapping = aes(
    x = fantasy_points)
) +
  geom_histogram(
    aes(y = after_stat(density)),
    color = "#000000",
    fill = "#0099F8"
  ) +
  geom_density(
    color = "#000000",
    fill = "#F85700",
    alpha = 0.6 # add transparency
  ) +
  geom_rug() +
  labs(
    x = "Fantasy Points",
    title = "Histogram of Fantasy Points with Overlaid Density and Rug Plot"
  ) +
  theme_classic() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Histogram with Overlaid Density and Rug Plot.
Figure 5.4: Histogram with Overlaid Density and Rug Plot.

5.3.4 Box-and-Whisker Plot

In a box-and-whisker plot, the box is created using the 1st and 3rd quartiles (i.e., the 25th and 75th percentiles, respectively). The length of the box is equal to the interquartile range, which is calculated as: \(\text{IQR} = Q_3 - Q_1\), where \(Q_3\) and \(Q_1\) are the third and first quartiles, respectively. The line in the middle of the box is located at the median (i.e., the 2nd quartile or 50th percentile). The whiskers commonly extend \(1.5 \times \text{IQR}\) units from the box. That is, the upper whisker is commonly located at \(1.5 \times \text{IQR}\) units above the third quartile. The lower whisker is commonly located at \(1.5 \times \text{IQR}\) units below the first quartile. The points represent extreme values (i.e., outliers) that are outside the whiskers.

A box-and-whisker plot of fantasy points is depicted in Figure 5.5.

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense %>%
    filter(position_group %in% c("QB","RB","WR","TE")),
  mapping = aes(
    x = position_group,
    y = fantasy_points,
    fill = position_group)
) +
  geom_boxplot(staplewidth = 0.25) +
  labs(
    x = "Position",
    y = "Fantasy Points",
    title = "Box-and-Whisker Plot of Fantasy Points by Position"
  ) +
  theme_classic() + 
  theme(
    legend.position = "none",
    axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Box-and-Whisker Plot.
Figure 5.5: Box-and-Whisker Plot.

5.3.5 Violin Plot

A violin plot of fantasy points is depicted in Figure 5.6.

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense %>%
    filter(position_group %in% c("QB","RB","WR","TE")),
  mapping = aes(
    x = position_group,
    y = fantasy_points,
    fill = position_group)
) +
  geom_violin(draw_quantiles = c(0.25, 0.5, 0.75)) +
  labs(
    x = "Position",
    y = "Fantasy Points",
    title = "Violin Plot of Fantasy Points by Position",
    subtitle = "Lines represent the 25th, 50th, and 75th quantiles"
  ) +
  theme_classic() + 
  theme(
    legend.position = "none",
    axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Violin Plot. Lines represent the 25th, 50th, and 75th quantiles.
Figure 5.6: Violin Plot. Lines represent the 25th, 50th, and 75th quantiles.

5.3.6 Ridgeline Plot

A ridgeline plot of fantasy points is depicted in Figure 5.7.

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense %>%
    filter(position_group %in% c("QB","RB","WR","TE")),
  mapping = aes(
    x = fantasy_points,
    y = position_group,
    group = position_group,
    fill = position_group)
) +
  ggridges::geom_density_ridges(
    rel_min_height = 0.0085, # remove trailing tails
  ) +
  labs(
    x = "Fantasy Points",
    y = "Position",
    title = "Ridgeline Plot of Fantasy Points by Position"
  ) +
  theme_classic() + 
  theme(
    legend.position = "none",
    axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Ridgeline Plot.
Figure 5.7: Ridgeline Plot.

We can add lines at the quartiles, as depicted in Figure 5.8.

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense %>%
    filter(position_group %in% c("QB","RB","WR","TE")),
  mapping = aes(
    x = fantasy_points,
    y = position_group,
    group = position_group,
    fill = factor(after_stat(quantile)))
) +
  ggridges::stat_density_ridges(
    rel_min_height = 0.0085, # remove trailing tails
    geom = "density_ridges_gradient",
    calc_ecdf = TRUE,
    quantiles = 4,
    quantile_lines = TRUE
  ) +
   scale_fill_viridis_d() + # use viridis color scheme
  labs(
    x = "Fantasy Points",
    y = "Position",
    title = "Ridgeline Plot of Fantasy Points by Position",
    subtitle = "Vertical lines represent the 25th, 50th, and 75th quantiles",
    fill = "Quartile"
  ) +
  theme_classic() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Ridgeline Plot. Lines represent the 25th, 50th, and 75th quantiles.
Figure 5.8: Ridgeline Plot. Lines represent the 25th, 50th, and 75th quantiles.

5.4 Scatterplot

As a tutorial, we walk through some of the (many) modifications that can be made to create an advanced, customized plot in ggplot2.

First, we prepare the data:

Code
# Subset Data
rb_seasonal <- player_stats_seasonal_offense %>% 
  filter(position_group == "RB")

5.4.1 Base Layer

Second, we create the base layer of the plot using the ggplot() function of the ggplot2 package, as in Figure 5.9. We specify the data object and the variables in the data object that are associated with the x- and y-axes:

Code
ggplot2::ggplot(
  data = rb_seasonal, # specify data object
  aes(
    x = age, # specify variable on x-axis
    y = rushing_yards)) # specify variable on y-axis
Base Plot.
Figure 5.9: Base Plot.

5.4.2 Add Points

Third, we create a scatterplot using the geom_point() function from the ggplot2 package, as in Figure 5.10:

Code
ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_yards)) +
  geom_point() # add points for scatterplot
Scatterplot.
Figure 5.10: Scatterplot.

5.4.3 Best-Fit Line

Fourth, we add a linear best-fit line using the geom_smooth(), as in Figure 5.11:

Code
ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_yards)) +
  geom_point() +
  geom_smooth(method = "lm") # add linear best-fit line
Scatterplot with Linear Best-Fit Line.
Figure 5.11: Scatterplot with Linear Best-Fit Line.

We could also estimate a quadratic polynomial best-fit line, as in Figure 5.12:

Code
ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_yards)) +
  geom_point() +
  geom_smooth(
    method = "lm",
    formula = y ~ poly(x, 2)) # add quadratic best-fit line
Scatterplot with Quadratic Best-Fit Line.
Figure 5.12: Scatterplot with Quadratic Best-Fit Line.

Or, we could estimate a smooth best-fit line using locally estimated scatterplot smoothing (LOESS) to allow for any form of nonlinearity, as in Figure 5.13:

Code
ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_yards)) +
  geom_point() +
  geom_smooth(method = "loess") # add smooth best-fit (LOESS) line
Scatterplot with Best-Fit Line Using Locally Estimated Scatterplot Smoothing (LOESS).
Figure 5.13: Scatterplot with Best-Fit Line Using Locally Estimated Scatterplot Smoothing (LOESS).

By default, the best-fit line is based on a generalized additive model, which allows for nonlinearity, as in Figure 5.14:

Code
ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_yards)) +
  geom_point() +
  geom_smooth() # add GAM best-fit line; same as specifying method = "gam"
Scatterplot with Best-Fit Line from Generalized Additive Model.
Figure 5.14: Scatterplot with Best-Fit Line from Generalized Additive Model.

5.4.4 Modify Axes

Then, we can change the axes, as in Figure 5.15:

Code
ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_yards)) +
  geom_point() +
  geom_smooth() +
  scale_x_continuous(
    expand = c(0,0), # set origin of x-axis to 0
    lim = c(20,40), # set limits of x-axis
    breaks = seq(from = 20, to = 40, by = 5) # specify x-axis labels
  ) +
  scale_y_continuous(
    expand = c(0,0), # set origin of y-axis to 0
    lim = c(0,NA), # set limits of y-axis
    breaks = seq(from = 0, to = 2500, by = 250) # specify y-axis labels
  )
Scatterplot with Modified Axes.
Figure 5.15: Scatterplot with Modified Axes.

5.4.5 Plot Labels

Then, we can add plot labels, as in Figure 5.16:

Code
ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_yards)) +
  geom_point() +
  geom_smooth() +
  scale_x_continuous(
    expand = c(0,0),
    lim = c(20,40),
    breaks = seq(from = 20, to = 40, by = 5)
  ) +
  scale_y_continuous(
    expand = c(0,0),
    lim = c(0,NA),
    breaks = seq(from = 0, to = 2500, by = 250)
  ) +
  labs( # add plot labels
    x = "Running Back's Age (years)",
    y = "Rushing Yards (Season)",
    title = "NFL Rushing Yards (Season) by Player Age",
    subtitle = "(Among Running Backs)"
  )
Scatterplot with Plot Labels.
Figure 5.16: Scatterplot with Plot Labels.

5.4.6 Theme

Then, we can use a theme such as the classic theme (theme_classic()) to make it more visually presentable, as in Figure 5.17:

Code
ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_yards)) +
  geom_point() +
  geom_smooth() +
  scale_x_continuous(
    expand = c(0,0),
    lim = c(20,40),
    breaks = seq(from = 20, to = 40, by = 5)
  ) +
  scale_y_continuous(
    expand = c(0,0),
    lim = c(0,NA),
    breaks = seq(from = 0, to = 2500, by = 250)
  ) +
  labs(
    x = "Running Back's Age (years)",
    y = "Rushing Yards (Season)",
    title = "NFL Rushing Yards (Season) by Player Age",
    subtitle = "(Among Running Backs)"
  ) +
  theme_classic() # use the classic theme
Scatterplot with Classic Theme.
Figure 5.17: Scatterplot with Classic Theme.

Or, we could use a different theme, such as the dark theme (theme_dark()) in Figure 5.18. For a list of themes available in ggplot2, see here: https://ggplot2-book.org/themes#sec-themes.

Code
ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_yards)) +
  geom_point() +
  geom_smooth() +
  scale_x_continuous(
    expand = c(0,0),
    lim = c(20,40),
    breaks = seq(from = 20, to = 40, by = 5)
  ) +
  scale_y_continuous(
    expand = c(0,0),
    lim = c(0,NA),
    breaks = seq(from = 0, to = 2500, by = 250)
  ) +
  labs(
    x = "Running Back's Age (years)",
    y = "Rushing Yards (Season)",
    title = "NFL Rushing Yards (Season) by Player Age",
    subtitle = "(Among Running Backs)"
  ) +
  theme_dark() # use the dark theme
Scatterplot with Dark Theme.
Figure 5.18: Scatterplot with Dark Theme.

5.4.7 Interactive

After creating our plot, we can make the plot interactive using the ggplotly() function from the plotly package, as in Figure 5.19.

Code
plot_ypcByPlayerAge <- ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_yards)) +
  geom_point(
    aes(
      text = player_display_name, # add player name for mouse over tooltip
      label = season)) + # add season for mouse over tooltip
  geom_smooth() +
  scale_x_continuous(
    expand = c(0,0),
    lim = c(20,40),
    breaks = seq(from = 20, to = 40, by = 5)
  ) +
  scale_y_continuous(
    expand = c(0,0),
    lim = c(0,NA),
    breaks = seq(from = 0, to = 2500, by = 250)
  ) +
  labs(
    x = "Running Back's Age (years)",
    y = "Rushing Yards (Season)",
    title = "NFL Rushing Yards (Season) by Player Age",
    subtitle = "(Among Running Backs)"
  ) +
  theme_classic()

ggplotly(plot_ypcByPlayerAge)
Figure 5.19: Interactive Scatterplot Using Plotly.

5.5 Line Chart

A bar plot of Tom Brady’s fantasy points by season is depicted in Figure 5.20.

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense %>%
    filter(player_display_name == "Tom Brady"),
  mapping = aes(
    x = season,
    y = fantasy_points
    )
) +
  geom_line(
    linewidth = 1.5,
    color = "blue"
  ) +
  labs(
    x = "Season",
    y = "Fantasy Points",
    title = "Bar Plot of Tom Brady's Fantasy Points by Season"
  ) +
  theme_classic() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Line Chart.
Figure 5.20: Line Chart.

5.5.1 With Highlighting

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense,
  mapping = aes(
    x = season,
    y = fantasy_points,
    group = player_id,
    color = player_display_name)
) +
  geom_line() +
  gghighlight::gghighlight(
    player_display_name == "Tom Brady",
    label_key = player_display_name) +
  labs(
    x = "Season",
    y = "Fantasy Points",
    title = "Fantasy Points by Season and Player",
    subtitle = "(Tom Brady in Red)"
  ) +
  theme_classic() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Line Chart with Highlighting.
Figure 5.21: Line Chart with Highlighting.

5.6 Bar Plot

To create a bar plot, we first compute summary statistics:

Code
confidenceLevel <- .95 # for 95% confidence interval

player_stats_seasonal_offense_summary <- player_stats_seasonal_offense %>%
    filter(position_group %in% c("QB","RB","WR","TE")) %>% 
  group_by(position_group) %>%
  summarise( 
    n = sum(!is.na(fantasy_points)),
    mean = mean(fantasy_points, na.rm = TRUE),
    sd = sd(fantasy_points, na.rm = TRUE)
  ) %>%
  mutate(se = sd/sqrt(n)) %>%
  mutate(
    ci_lower = mean - qt(p = 1 - (1 - confidenceLevel) / 2, df = n - 1) * se,
    ci_upper = mean + qt(p = 1 - (1 - confidenceLevel) / 2, df = n - 1) * se
  )

The summary statistics are in Table 5.1.

Code
player_stats_seasonal_offense_summary
Table 5.1: Table of Summary Statistics.

A bar plot of fantasy points by position is depicted in Figure 5.22.

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense_summary,
  mapping = aes(
    x = position_group,
    y = mean,
    fill = position_group
    )
) +
  geom_bar(
    stat = "identity") +
  labs(
    x = "Position",
    y = "Fantasy Points",
    title = "Bar Plot of Fantasy Points by Position"
  ) +
  theme_classic() + 
  theme(legend.position = "none") +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Bar Plot.
Figure 5.22: Bar Plot.

5.6.1 With Error Bars

Based on the summary statistics in Table 5.1, we create a bar plot with bars representing the 95% confidence interval in Figure 5.23.

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense_summary %>%
    filter(position_group %in% c("QB","RB","WR","TE")),
  mapping = aes(
    x = position_group,
    y = mean,
    fill = position_group
    )
) +
  geom_bar(
    stat = "identity") +
  geom_errorbar(
    aes(
      ymin = ci_lower,
      ymax = ci_upper),
    width = 0.2,
    color = "black"
  ) +
  labs(
    x = "Position",
    y = "Fantasy Points",
    title = "Bar Plot of Fantasy Points by Position"
  ) +
  theme_classic() + 
  theme(legend.position = "none") +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Bar Plot with Bars Representing the 95% Confidence Interval.
Figure 5.23: Bar Plot with Bars Representing the 95% Confidence Interval.

5.6.2 Modified Color Scheme

We can also modify the color scheme, as in Figure 5.24

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense_summary %>%
    filter(position_group %in% c("QB","RB","WR","TE")),
  mapping = aes(
    x = position_group,
    y = mean,
    fill = position_group
    )
) +
  geom_bar(
    stat = "identity") +
  scale_fill_brewer(palette = "Dark2") +
  geom_errorbar(
    aes(
      ymin = ci_lower,
      ymax = ci_upper),
    width = 0.2,
    color = "black"
  ) +
  labs(
    x = "Position",
    y = "Fantasy Points",
    title = "Bar Plot of Fantasy Points by Position"
  ) +
  theme_classic() + 
  theme(legend.position = "none") +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) # horizontal y-axis title
Bar Plot with Bars Representing the 95% Confidence Interval.
Figure 5.24: Bar Plot with Bars Representing the 95% Confidence Interval.

5.7 Faceting

Code
ggplot2::ggplot(
  data = player_stats_seasonal_offense %>% 
    filter(position_group %in% c("QB","RB","WR","TE")),
  aes(
    x = age,
    y = fantasy_points)) +
  geom_point() +
  geom_smooth() +
  scale_x_continuous(
    expand = c(0,0)
  ) +
  scale_y_continuous(
    expand = c(0,0),
    lim = c(0,NA)
  ) +
  labs(
    x = "Player's Age (years)",
    y = "Fantasy Points (Season)",
    title = "Fantasy Points (Season) by Player Age"
  ) +
  theme_bw() +
  facet_wrap(vars(position_group)) # facet by position_group
Faceted Scatterplot.
Figure 5.25: Faceted Scatterplot.

5.8 Examples

5.8.1 Players

5.8.1.1 Running Back Performance By Player Age

Code
# Prepare Data
rushing_attempts <- nfl_pbp %>% 
  dplyr::filter(season_type == "REG") %>% 
  dplyr::filter(
    rush == 1,
    rush_attempt == 1,
    qb_scramble == 0,
    qb_dropback == 0,
    !is.na(rushing_yards))

rb_yardsPerCarry <- rushing_attempts %>% 
  dplyr::group_by(rusher_id, season) %>% 
  dplyr::summarise(
    ypc = mean(rushing_yards, na.rm = TRUE),
    rush_attempts = n(),
    .groups = "drop") %>% 
  dplyr::ungroup() %>% 
  dplyr::left_join(
    player_stats_seasonal_offense,
    by = c("rusher_id" = "player_id", "season")
  ) %>% 
  dplyr::filter(
    position_group == "RB",
    rush_attempts >= 50)
5.8.1.1.1 Rushing Yards Per Carry

Rushing yards per carry over the course of the season is depicted as a function of the Running Back’s age in Figure 5.26.

Code
plot_ypcByPlayerAge2 <- ggplot2::ggplot(
  data = rb_yardsPerCarry,
  aes(
    x = age,
    y = ypc)) +
  geom_point(
    aes(
      text = player_display_name,
      label = season)) +
  geom_smooth() +
  labs(
    x = "Running Back's Age (years)",
    y = "Rushing Yards Per Carry (Season)",
    title = "NFL Rushing Yards Per Carry (Season) by Player Age",
    subtitle = "(minimum 50 rushing attempts)"
  ) +
  theme_classic()

ggplotly(plot_ypcByPlayerAge2)
Figure 5.26: Rushing Yards Per Carry (Season) by Player Age.
5.8.1.1.2 Rushing EPA Per Season

Rushing expected points added (EPA) over the course of the season is depicted as a function of the Running Back’s age in Figure 5.27.

Code
plot_rushEPAbyPlayerAge <- ggplot2::ggplot(
  data = rb_seasonal,
  aes(
    x = age,
    y = rushing_epa)) +
  geom_point(
    aes(
      text = player_display_name,
      label = season)) +
  geom_smooth() +
  labs(
    x = "Running Back's Age (years)",
    y = "Rushing EPA (Season)",
    title = "NFL Rushing Expected Points Added (Season) by Player Age"
  ) +
  theme_classic()

ggplotly(plot_rushEPAbyPlayerAge)
Figure 5.27: Rushing Expected Points Added (Season) by Player Age.

5.8.2 Teams

5.8.2.1 Defensive and Offensive EPA per Play

Expected points added (EPA) per play by the team with possession.

Code
pbp_regularSeason <- nfl_pbp %>% 
  dplyr::filter(
    season == 2024,
    season_type == "REG") %>%
  dplyr::filter(!is.na(posteam) & (rush == 1 | pass == 1))

epa_offense <- pbp_regularSeason %>%
  dplyr::group_by(team = posteam) %>%
  dplyr::summarise(off_epa = mean(epa, na.rm = TRUE))

epa_defense <- pbp_regularSeason %>%
  dplyr::group_by(team = defteam) %>%
  dplyr::summarise(def_epa = mean(epa, na.rm = TRUE))

epa_combined <- epa_offense %>%
  dplyr::inner_join(
    epa_defense,
    by = "team")

Defensive EPA per play during the 2024 NFL season is depicted as a function of offensive EPA per play in Figure 5.28.

Code
ggplot2::ggplot(
  data = epa_combined,
  aes(
    x = off_epa,
    y = def_epa)) +
  nflplotR::geom_mean_lines(
    aes(
      x0 = off_epa ,
      y0 = def_epa)) +
  nflplotR::geom_nfl_logos(
    aes(
      team_abbr = team),
      width = 0.065,
      alpha = 0.7) +
  labs(
    x = "Offense EPA/play",
    y = "Defense EPA/play",
    title = "2024 NFL Offensive and Defensive EPA per Play"
  ) +
  theme_classic() +
  theme(axis.title.y = element_text(angle = 0, vjust = 0.5)) + # horizontal y-axis title
  scale_y_reverse()
2024 NFL Offensive and Defensive EPA Per Play.
Figure 5.28: 2024 NFL Offensive and Defensive EPA Per Play.

5.9 Conclusion

5.10 Session Info

Code
sessionInfo()
R version 4.4.2 (2024-10-31)
Platform: x86_64-pc-linux-gnu
Running under: Ubuntu 22.04.5 LTS

Matrix products: default
BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.20.so;  LAPACK version 3.10.0

locale:
 [1] LC_CTYPE=C.UTF-8       LC_NUMERIC=C           LC_TIME=C.UTF-8       
 [4] LC_COLLATE=C.UTF-8     LC_MONETARY=C.UTF-8    LC_MESSAGES=C.UTF-8   
 [7] LC_PAPER=C.UTF-8       LC_NAME=C              LC_ADDRESS=C          
[10] LC_TELEPHONE=C         LC_MEASUREMENT=C.UTF-8 LC_IDENTIFICATION=C   

time zone: UTC
tzcode source: system (glibc)

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
 [1] lubridate_1.9.3   forcats_1.0.0     stringr_1.5.1     dplyr_1.1.4      
 [5] purrr_1.0.2       readr_2.1.5       tidyr_1.3.1       tibble_3.2.1     
 [9] tidyverse_2.0.0   ggridges_0.5.6    gghighlight_0.4.1 plotly_4.10.4    
[13] ggplot2_3.5.1     nflplotR_1.4.0   

loaded via a namespace (and not attached):
 [1] gtable_0.3.6       xfun_0.49          htmlwidgets_1.6.4  ggrepel_0.9.6     
 [5] lattice_0.22-6     tzdb_0.4.0         vctrs_0.6.5        tools_4.4.2       
 [9] crosstalk_1.2.1    generics_0.1.3     fansi_1.0.6        pkgconfig_2.0.3   
[13] Matrix_1.7-1       data.table_1.16.2  RColorBrewer_1.1-3 gt_0.11.1         
[17] lifecycle_1.0.4    compiler_4.4.2     farver_2.1.2       munsell_0.5.1     
[21] htmltools_0.5.8.1  yaml_2.3.10        lazyeval_0.2.2     pillar_1.9.0      
[25] cachem_1.1.0       magick_2.8.5       nlme_3.1-166       tidyselect_1.2.1  
[29] digest_0.6.37      stringi_1.8.4      labeling_0.4.3     splines_4.4.2     
[33] fastmap_1.2.0      grid_4.4.2         colorspace_2.1-1   cli_3.6.3         
[37] magrittr_2.0.3     utf8_1.2.4         withr_3.0.2        nflreadr_1.4.1    
[41] scales_1.3.0       ggpath_1.0.2       timechange_0.3.0   rmarkdown_2.29    
[45] httr_1.4.7         hms_1.1.3          memoise_2.0.1      evaluate_1.0.1    
[49] knitr_1.49         viridisLite_0.4.2  mgcv_1.9-1         rlang_1.1.4       
[53] Rcpp_1.0.13-1      glue_1.8.0         xml2_1.3.6         jsonlite_1.8.9    
[57] R6_2.5.1          

Feedback

Please consider providing feedback about this textbook, so that I can make it as helpful as possible. You can provide feedback at the following link: https://forms.gle/LsnVKwqmS1VuxWD18

Email Notification

The online version of this book will remain open access. If you want to know when the print version of the book is for sale, enter your email below so I can let you know.