Part 1: National Basketball Association Players The National Basketball Association (NBA) is an American professional basketball league consisting of 30 teams subdivided into two conferences (Eastern and Western) which are in turn subdivided into six divisions (Atlantic, Central, and Southeast in the Eastern Conference, and Northwest, Pacific, and Southwest in the Western Conference).
The league conducts an annual championship tournament (“Season”), starting around October and ending around June of the next year. (For the purposes of the following, “X Season” for year X refers to the season starting in October of X and ending in June of X+1 .) From 2005 to 2020, the championship games played by the league involved 2234 players (in the sense that they’ve played at least one game). During a given season, a player can play for more than one team in a number of situations. These include trades, in which a player moves from one team to another mid-season.
The data used here were compiled by Nathan Lauga and posted on Kaggle. To save you time, these data have already been “tidied” for you, but you may need to make further transformations or summaries. The following files are provided. If you would like some additional ones during the lab, I may be able to put them together.
On the course web site, you will find a number of files:
player_games_played.csv
player_games_played <- read.csv("player_games_played.csv")
team_games_played <- read.csv("team_games_played.csv")
scoring_rate <- read.csv("scoring_rate.csv")
divisions <- read.csv("divisions.csv")
What are the consistent features of these plots? Which years stand out? (A quick Internet search should tell you what happened during those seasons.) Annotate the plot to tell the story at a glance.
Does breaking teams down by division and conference add to the story? How?
library(tidyverse)
## ── Attaching core tidyverse packages ──────────────────────── tidyverse 2.0.0 ──
## ✔ dplyr 1.1.4 ✔ readr 2.1.5
## ✔ forcats 1.0.0 ✔ stringr 1.5.1
## ✔ ggplot2 3.5.1 ✔ tibble 3.2.1
## ✔ lubridate 1.9.3 ✔ tidyr 1.3.1
## ✔ purrr 1.0.2
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## ✖ dplyr::filter() masks stats::filter()
## ✖ dplyr::lag() masks stats::lag()
## ℹ Use the conflicted package (<http://conflicted.r-lib.org/>) to force all conflicts to become errors
library(ggridges)
library(ggplot2)
## 绘制ggplot,x为比赛场数,y为赛季,反转赛季顺序,让最近的赛季靠近顶部
p <- ggplot(team_games_played,
aes(
x = Games,
y = factor(Season) %>% fct_rev()
)
) +
##绘制山峦图,alpha:设置透明度,col = 设置山峦边界颜色,scale:设置山峦的高度比例
##quantile_lines = TRUE 添加分位线,quantiles = 2 表示中位数线
geom_density_ridges(alpha = 0.7, col = "darkgray",
scale = 1, quantile_lines = TRUE,
quantiles = 2) +
##theme_ridges():优化山峦图的主题样式
theme_ridges() +
labs(y = "Season", x = "Games played by a team")
#添加注释;添加矩形区域标注;矩形的 X 范围(60 到 110 场);矩形的 Y 范围(赛季从第 1 到第 3,稍微偏移以调整位置);矩形内部无填充;矩形边框颜色为红色
p2 <- p + annotate("rect", xmin = 60, xmax = 110,
ymin = 1 - 0.1, ymax = 3 - 0.1,
fill = NA, col = "red") +
#添加文本注释;文本位置;标注为 "COVID-19";文本左对齐;文本颜色为红色
annotate("text", x = 111, y = 2.5,
label = "COVID-19", hjust = "left", col = 2) +
#同上,添加look out影响
annotate("rect", xmin = 60, xmax = 100,
ymin = 10 - 0.1, ymax = 11 + 0.1,
fill = NA, col = 2) +
annotate("text", x = 101, y = 10.5,
label = "Lock-out", hjust = "left", col = 2)
print(p2)
## Picking joint bandwidth of 3.06
We can use the fill colour aesthetic to break the teams down by division
and/or conference. Breaking down by division, we see that the lock-out
affected both conferences equally, whereas COVID-19 affected the Eastern
Conference more.
#同上,增加了分赛区数据
p <- inner_join(team_games_played, divisions) %>%
ggplot(aes(
x = Games,
y = factor(Season) %>% fct_rev(),
#按赛区区分颜色
fill = Conference
)
) +
geom_density_ridges(alpha = 0.7, col = "darkgray",
scale = 1, quantile_lines = TRUE,
quantiles = 2) +
theme_ridges() +
labs(y = "Season", x = "Games played by a team")
## Joining with `by = join_by(Team)`
p2 <- p + annotate("rect", xmin = 60, xmax = 110,
ymin = 1 - 0.1, ymax = 3 - 0.1,
fill = NA, col = 2) +
annotate("text", x = 111, y = 2.5,
label = "COVID-19", hjust = "left", col = 2) +
annotate("rect", xmin = 60, xmax = 100,
ymin = 10 - 0.1, ymax = 11 + 0.1,
fill = NA, col = 2) +
annotate("text", x = 101, y = 10.5,
label = "Lock-out", hjust = "left", col = 2)
print(p2)
## Picking joint bandwidth of 3.26
We can also look at divisions within conferences. Here, note the use of
substr() to abbreviate the conference:
p <- inner_join(team_games_played, divisions) %>%
ggplot(aes(
x = Games,
y = factor(Season) %>% fct_rev(),
#paste0()拼接字符串;substr()提取字符串 Conference 的首字母,加入“:”,再加入分区Division
fill = paste0(substr(Conference, 1,1), ": ", Division)
)
) +
geom_density_ridges(alpha = 0.4, col = "darkgray",
scale = 1, quantile_lines = TRUE,
quantiles = 2) +
theme_ridges() +
labs(y = "Season", x = "Games played by a team", fill = "Division")
## Joining with `by = join_by(Team)`
p2 <- p + annotate("rect", xmin = 60, xmax = 110,
ymin = 1 - 0.1, ymax = 3 - 0.1,
fill = NA, col = 2) +
annotate("text", x = 111, y = 2.5,
label = "COVID-19", hjust = "left", col = 2) +
annotate("rect", xmin = 60, xmax = 100,
ymin = 10 - 0.1, ymax = 11 + 0.1,
fill = NA, col = 2) +
annotate("text", x = 101, y = 10.5,
label = "Lock-out", hjust = "left", col = 2)
print(p2)
## Picking joint bandwidth of 3.18
(b)Now, make a similar visualisation of the distribution of the number of games a player plays during each season. What patterns do you see? Annotate the plot to tell the story at a glance.
library(tidyverse)
library(ggridges)
##整合数据集,按照赛季与球员分组,对每个球员的比赛场次求和
p <- player_games_played %>%
group_by(Season, Player) %>%
summarise(Games = sum(Games)) %>%
##x表示球员在赛季中的比赛场次;y表示赛季,使用 sort() 和 decreasing = TRUE 将赛季按从新到旧的顺序排列
ggplot(aes(x = Games,
y = factor(Season, levels = sort(unique(Season),
decreasing = TRUE)))) +
##同上,绘制山峦图
geom_density_ridges(alpha = 0.7, col = "darkgray",
scale = 1, quantile_lines = TRUE, quantiles = 2) +
theme_ridges() +
labs(y = "Season", x = "Games played by a player") +
#限制 X 轴的下限为 0,上限为自动计算
xlim(0, NA)
## `summarise()` has grouped output by 'Season'. You can override using the
## `.groups` argument.
##同上
p2 <- p + annotate("rect", xmin = 1, xmax = 110,
ymin = 1 - 0.1, ymax = 3 - 0.1,
fill = NA, col = 2) +
annotate("text", x = 111, y = 2.5,
label = "COVID-19", hjust = "left", col = 2) +
annotate("rect", xmin = 1, xmax = 100,
ymin = 10 - 0.1, ymax = 11 + 0.1,
fill = NA, col = 2) +
annotate("text", x = 101, y = 10.5,
label = "Lock-out", hjust = "left", col = 2) +
##添加竖向方框
annotate("rect", xmin = 0, xmax = 25,
ymin = 1 - 0.2, ymax = 17 - 0.1,
fill = NA, col = 3) +
annotate("text", x = 26, y = 17 - 0.3,
label = "Reserve players", hjust = "left", col = 3)
print(p2)
## Picking joint bandwidth of 8.35
(c) We now want to look at whether there is a relationship between a
player being more “productive” in terms of number of points scored per
minute on the court and the amount of time they are allocated on the
court. Produce a plot, and highlight and label notable players and
seasons, and refine it for aesthetics and accessibility. Note that this
example plot represents a starting point and neglects those
considerations:
#使用 ggrepel 包自动调整文本标签,避免标签与点或其他标签重叠
library(ggrepel)
##筛选出上场时间至少 20 分钟的球员
scoring_rate %>% filter(Minutes >= 20) %>%
##x为登场时间,y为分均得分
ggplot(aes(x = Minutes, y = Scored / Minutes)) +
##添加散点图,透明度0.1,添加趋势线,不显示置信区间了
geom_point(alpha = .1) + geom_smooth(se = FALSE) +
##设置上限为6000分钟
xlim(NA, 6000) +
#标注特定球员
geom_label_repel(
#登场超过20分钟的球员中
data = scoring_rate %>% filter(Minutes >= 20),
#标注出名字,如果赛季总时长大于4000,分钟场均得分>0.6,""其他不标注
aes(Minutes, Scored/Minutes,
label = ifelse( Minutes >= 4000 | Scored / Minutes > 0.6,
paste(Player, Season), ""))) +
labs(x = "Amount of time spent on court (minutes)",
y = "Performance (points scored per minute)") +
ggtitle("Performance of players who spent at least 20 minutes on the court")
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
## Warning: ggrepel: 14 unlabeled data points (too many overlaps). Consider
## increasing max.overlaps
##使用 ggrepel 包自动调整文本标签,避免标签与点或其他标签重叠
library(ggrepel)
d <- scoring_rate %>%
group_by(Season) %>%
#保留数据框中的所有列;按 Minutes(上场时间)从高到低对球员排名,排名的结果存储在 Rank 列中
summarise(across(everything()), Rank = rank(-Minutes)) %>%
#筛选每个赛季排名前 100 的球员(上场时间最多的球员)
filter(Rank < 100) %>% ungroup()
## Warning: Returning more (or less) than 1 row per `summarise()` group was deprecated in
## dplyr 1.1.0.
## ℹ Please use `reframe()` instead.
## ℹ When switching from `summarise()` to `reframe()`, remember that `reframe()`
## always returns an ungrouped data frame and adjust accordingly.
## Call `lifecycle::last_lifecycle_warnings()` to see where this warning was
## generated.
## `summarise()` has grouped output by 'Season'. You can override using the
## `.groups` argument.
##同上,如果球员得分效率(Scored / Minutes)大于 0.6,则显示球员的姓名和赛季信息(paste(Player, Season))
ggplot(d, aes(x = Rank, y = Scored / Minutes)) +
geom_point(alpha = .1) + geom_smooth(se = FALSE) +
geom_label_repel(
data = d,
aes(Rank, Scored / Minutes,
label = ifelse(Scored / Minutes > 0.6, paste(Player, Season), ""))) +
scale_x_reverse() +
labs(x = "Amount of time spent on court (rank within season)",
y = "Performance (points scored per minute)",
title = "Player performance and time spent on court",
subtitle = "Players with high performance rate are identified.")
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
(e) Lastly, consider LeBron James, considered by many to be one of the
greatest basketball players in the history of the sport. On the plot
from (c) and/or (d) highlight James’s trajectory.
Again, the following plot is just an example; yours should be better aesthetically.
# 找出LBJ
james <- scoring_rate %>%
filter(Player == "LeBron James") %>%
arrange(Season)
#过滤上场时间大于 30 分钟的球员
scoring_rate %>% filter(Minutes > 30) %>%
ggplot(aes(x = Minutes, y = Scored / Minutes)) +
geom_point(alpha = 0.1) + geom_smooth(se = FALSE) +
###突出显示 LeBron James 的数据,使用红色点标记 LeBron James 的表现
geom_point(data = james,
aes(x = Minutes, y = Scored / Minutes),
col = 2) +
##根据 LeBron James 的数据点按赛季连接成折线,展示他的表现趋势
geom_path(data = james,
aes(x = Minutes, y = Scored/Minutes),
col = 2) +
##筛选 LeBron James 的第一个赛季和最后一个赛季数据,使用 range(Season) 自动获取起点和终点赛季
geom_text_repel(
data = james %>% filter(Season %in% range(Season)),
aes(x = Minutes, y = Scored / Minutes,
label = Season),
col = 2) +
labs(x = "Amount of time spent on court (minutes)",
y = "Performance (points scored per minute)",
title = "Lebron James's time spent on court and performance over time")
## `geom_smooth()` using method = 'gam' and formula = 'y ~ s(x, bs = "cs")'
Part 2: Customising plots
library(ggplot2)
library(tidyverse)
library(broom)
data(mpg)
lmfit <- lm(hwy ~ I(displ/cyl) + factor(cyl), data = mpg)
plot.data <- augment(lmfit, mpg, interval = "confidence")
# 选择颜色
library(wesanderson)
plot.colours <- wes_palette("Darjeeling1")
plot.data %>%
ggplot(aes(x = displ/cyl, y = hwy,
colour = factor(cyl),
group = factor(cyl))) +
geom_point() +
#绘制之心区间带
geom_ribbon(aes(ymin = .lower, ymax = .upper), alpha = 0.2, color = FALSE) +
geom_line(aes(y = .fitted)) +
labs(x = "Displacement per cylinder",
y = "Highway fuel efficiency",
col = "Cylinders",
fill = "Cylinders") +
#增加图标标题
ggtitle("Highway fuel efficiency decreases with higher displacement") +
# 自定义颜色
scale_colour_manual(values = plot.colours,
name = "Cylinders",
# 更改图例中圆柱体的顺序
breaks = c("8", "6", "5", "4")) +
# 消除灰色背景
theme_bw() +
#更改标题为衬线字体
#注意:不需要将其他字体更改为sans-serif,
#所有字体默认为无衬线字体
theme(plot.title = element_text(family = "serif"),
#改变轴标题的大小
axis.title = element_text(size = 14))
library(RColorBrewer)
# 看看有啥颜色
display.brewer.all(colorblindFriendly = T)
plot.colours <- brewer.pal(n = 4, name = "Set2")
# choose a colour palette with red in it
library(wesanderson)
plot.colours <- wes_palette("Zissou1")
# make sure red is "8" by putting them in the right order
# the fifth colour is red, so I match the 5th colour to "8" in the
# "breaks" order
# you would put the following in the ggplot call:
scale_colour_manual(values = c(plot.colours[5], plot.colours[1:3]),
name = "Cylinders",
# change order of cylinders in legend
breaks = c("8", "6", "5", "4"))
## <ggproto object: Class ScaleDiscrete, Scale, gg>
## aesthetics: colour
## axis_order: function
## break_info: function
## break_positions: function
## breaks: 8 6 5 4
## call: call
## clone: function
## dimension: function
## drop: TRUE
## expand: waiver
## get_breaks: function
## get_breaks_minor: function
## get_labels: function
## get_limits: function
## get_transformation: function
## guide: legend
## is_discrete: function
## is_empty: function
## labels: waiver
## limits: NULL
## make_sec_title: function
## make_title: function
## map: function
## map_df: function
## n.breaks.cache: NULL
## na.translate: TRUE
## na.value: grey50
## name: Cylinders
## palette: function
## palette.cache: NULL
## position: left
## range: environment
## rescale: function
## reset: function
## train: function
## train_df: function
## transform: function
## transform_df: function
## super: <ggproto object: Class ScaleDiscrete, Scale, gg>
label.data <- plot.data %>%
group_by(cyl) %>%
##用 round(mean(hwy)) 计算并四舍五入到整数,将结果拼接成标签字符串,格式为 mean=XX
summarise(mean.hwy = paste0("mean=", round(mean(hwy))))
plot.data %>%
ggplot(aes(x = displ/cyl, y = hwy,
colour = factor(cyl), group = factor(cyl))) +
geom_point() +
geom_ribbon(aes(ymin = .lower, ymax = .upper), alpha = 0.2, color = FALSE) +
geom_line(aes(y = .fitted)) +
#facet_wrap():按照气缸数(cyl)分面,每个分面显示一个气缸数的图形
#factor(cyl) ~ .:将气缸数转为分类变量,作为分面的依据;设置分面标题的格式,显示变量名和变量值:例如,标题为 cyl: 4
facet_wrap(factor(cyl) ~ ., labeller = label_both) +
labs(x = "Displacement per cylinder",
y = "Highway fuel efficiency",
col = "Cylinders",
fill = "Cylinders") +
geom_text(data = label.data,
#添加固定标签位置;标签内容为气缸数的平均燃油效率(mean.hwy)
mapping = aes(x = 0.75, y = 40, label = mean.hwy),
colour = "black")