if (!require("pak")) install.packages("pak")
::pak("mrcaseb/nbaplotR") pak
Using the NBA API in R
news
code
analysis
nba_api is a Python client for accessing data from www.nba.com. This post presents an example of using nba_api
to create a data viz. This example begins by using reticulate::import()
to import nba_api
. Before doing this, we must:
Install Python and configure R to use Python using the reticulate package;
Install
nba_api
in Python.
A minimal working example for this setup would be useful. I do not have one, because my process involved the Anaconda GUI and so it is not reproducible.
For data viz, we use the nbaplotR
package, which provides a ggplot2
geom for plotting NBA and WNBA logos. This package is not available on CRAN – the developer recommends installing from Github using pak::pak()
:
# Load R packages and Python modules ------
library(reticulate)
library(dplyr)
library(ggplot2)
library(ggiraph)
library(nbaplotR)
<- reticulate::import("nba_api")
nba_api <- nba_api$stats$endpoints$leaguedashteamstats$LeagueDashTeamStats
LeagueDashTeamStats
# Pull and wrangle data from nba.com ------
<- LeagueDashTeamStats(
my_df1 season = '2022-23',
season_type_all_star = 'Regular Season'
$get_data_frames()[[1]] %>%
)mutate(
TEAM_ABBR = valid_team_names("NBA")[c(1, 3, 2, 4:25, 27, 26, 28:30)]
)
# Plot data ------
<- my_df1 %>%
my_ggobj ggplot(aes(x = REB, y = PTS)) +
geom_nba_logos(
aes(team_abbr = TEAM_ABBR),
width = 0.075,
height = 0.075
+
) theme_bw()
girafe(ggobj = my_ggobj)