-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdata-visualization.qmd
1209 lines (1024 loc) · 36.8 KB
/
data-visualization.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Data Visualization {#sec-dataVisualization}
## Getting Started {#sec-dataVisualizationGettingStarted}
### Load Packages {#sec-dataVisualizationLoadPackages}
```{r}
library("nflplotR")
library("plotly")
library("gghighlight")
library("ggridges")
library("tidyverse")
```
### Load Data {#sec-dataVisualizationLoadData}
```{r}
#| eval: false
#| include: false
load(file = file.path(path, "/OneDrive - University of Iowa/Teaching/Courses/Fantasy Football/Data/nfl_pbp.RData", fsep = ""))
load(file = file.path(path, "/OneDrive - University of Iowa/Teaching/Courses/Fantasy Football/Data/player_stats_weekly.RData", fsep = ""))
load(file = file.path(path, "/OneDrive - University of Iowa/Teaching/Courses/Fantasy Football/Data/player_stats_seasonal.RData", fsep = ""))
```
```{r}
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 @sec-calculatePlayerAge.
## Overview {#sec-dataVisualizationOverview}
### Principles of Graphic Design {#sec-dataVisualizationOverviewGraphicDesign}
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.
### Principles of Data Visualization {#sec-dataVisualizationOverviewPrinciples}
Data visualization involves graphic design in a particular domain—the visualization of data (numeric-derived information).
@Schwabish2021 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, @Schwabish2021 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, @Schwabish2021 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, @Schwabish2021 advocates [breaking it up into multiple charts](#sec-faceting) (i.e., facets, trellis charts, or small multiples).
An example of [faceted charts](#sec-faceting) is depicted in @fig-facetedScatterplot.
"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 @Schwabish2021, 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, @Tufte2001 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 -@Schwabish2021 principles of showing the data and reducing the clutter.
@Tufte2001 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 [-@Tufte2001, p. 77]
@Tufte2001 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 @fig-exampleDataVisualization.
```{r}
#| label: fig-exampleDataVisualization
#| fig-cap: "Example Figure that Applies the Principles of Data Visualization."
#| fig-alt: "Example Figure that Applies the Principles of Data Visualization."
#| code-fold: true
confidenceLevel <- .95 # for 95% confidence interval
player_stats_seasonal_offense_summary <- player_stats_seasonal %>%
filter(position_group %in% c("QB","RB","WR","TE")) %>%
group_by(position_group) %>%
summarise(
n = sum(!is.na(fantasyPoints)),
mean = mean(fantasyPoints, na.rm = TRUE),
sd = sd(fantasyPoints, 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
```
### Creating Data Visualizations in `R` {#sec-dataVisualizationOverviewInR}
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*](https://ggplot2-book.org) [@ggplot3rdEd] and [*`R` Graphics Cookbook: Practical Recipes for Visualizing Data*](https://r-graphics.org) [@Chang2018].
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](#sec-wideToLong) (as opposed to [wide form](#sec-longToWide)).
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 [@Schwabish2021].
For examples of highlighting in figures, see Figures [-@fig-lineChartHighlighting] (@sec-lineChartHighlighting) and [-@fig-simulationOf10CoinFlips].
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 @fig-barPlotColorScheme (@sec-barPlotModifiedColorScheme).
There are a variety of resources for color schemes that are accessible to color-blind viewers:
- <https://www.datylon.com/blog/data-visualization-for-colorblind-readers> (archived at <https://perma.cc/7VTA-Y8YS>)
- <https://cran.r-project.org/web/packages/viridis/vignettes/intro-to-viridis.html> (archived at <https://perma.cc/NK9K-HL7L>)
- @Nunez2018
## Univariate Distribution {#sec-univariateDistribution}
For ways of visualizing univariate distributions, see [here](https://z3tt.github.io/beyond-bar-and-box-plots) (archived at <https://perma.cc/EEJ8-LND2>).
### Histogram {#sec-histogram}
A histogram of fantasy points is depicted in @fig-histogram.
```{r}
#| label: fig-histogram
#| fig-cap: "Histogram of Fantasy Points."
#| fig-alt: "Histogram of Fantasy Points."
ggplot2::ggplot(
data = player_stats_seasonal %>%
filter(position_group %in% c("QB","RB","WR","TE")),
mapping = aes(
x = fantasyPoints)
) +
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
```
### Density Plot {#sec-densityPlot}
A histogram of fantasy points is depicted in @fig-density.
```{r}
#| label: fig-density
#| fig-cap: "Density Plot of Fantasy Points by Position."
#| fig-alt: "Density Plot of Fantasy Points by Position."
ggplot2::ggplot(
data = player_stats_seasonal %>%
filter(position_group %in% c("QB","RB","WR","TE")),
mapping = aes(
x = fantasyPoints,
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
```
### Histogram with Overlaid Density and Rug Plot {#sec-histogramDensity}
A histogram of fantasy points with an overlaid density and rug plot is depicted in @fig-histogramDensity.
```{r}
#| label: fig-histogramDensity
#| fig-cap: "Histogram with Overlaid Density and Rug Plot."
#| fig-alt: "Histogram with Overlaid Density and Rug Plot."
ggplot2::ggplot(
data = player_stats_seasonal %>%
filter(position_group %in% c("QB","RB","WR","TE")),
mapping = aes(
x = fantasyPoints)
) +
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
```
### Box-and-Whisker Plot {#sec-boxAndWhiskerPlot}
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 @fig-boxAndWhisker.
```{r}
#| label: fig-boxAndWhisker
#| fig-cap: "Box-and-Whisker Plot."
#| fig-alt: "Box-and-Whisker Plot."
ggplot2::ggplot(
data = player_stats_seasonal %>%
filter(position_group %in% c("QB","RB","WR","TE")),
mapping = aes(
x = position_group,
y = fantasyPoints,
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
```
### Violin Plot {#sec-violinPlot}
A violin plot of fantasy points is depicted in @fig-violin.
```{r}
#| label: fig-violin
#| fig-cap: "Violin Plot. Lines represent the 25th, 50th, and 75th quantiles."
#| fig-alt: "Violin Plot. Lines represent the 25th, 50th, and 75th quantiles."
ggplot2::ggplot(
data = player_stats_seasonal %>%
filter(position_group %in% c("QB","RB","WR","TE")),
mapping = aes(
x = position_group,
y = fantasyPoints,
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
```
### Ridgeline Plot {#sec-ridgelinePlot}
A ridgeline plot of fantasy points is depicted in @fig-ridgeline1.
```{r}
#| label: fig-ridgeline1
#| fig-cap: "Ridgeline Plot."
#| fig-alt: "Ridgeline Plot."
ggplot2::ggplot(
data = player_stats_seasonal %>%
filter(position_group %in% c("QB","RB","WR","TE")),
mapping = aes(
x = fantasyPoints,
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
```
We can add lines at the quartiles, as depicted in @fig-ridgeline2.
```{r}
#| label: fig-ridgeline2
#| fig-cap: "Ridgeline Plot. Lines represent the 25th, 50th, and 75th quantiles."
#| fig-alt: "Ridgeline Plot. Lines represent the 25th, 50th, and 75th quantiles."
ggplot2::ggplot(
data = player_stats_seasonal %>%
filter(position_group %in% c("QB","RB","WR","TE")),
mapping = aes(
x = fantasyPoints,
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
```
## Scatterplot {#sec-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:
```{r}
# Subset Data
rb_seasonal <- player_stats_seasonal %>%
filter(position_group == "RB")
```
### Base Layer {#sec-scatterplotBaseLayer}
Second, we create the base layer of the plot using the `ggplot()` function of the `ggplot2` package, as in @fig-scatterplot1.
We specify the data object and the variables in the data object that are associated with the x- and y-axes:
```{r}
#| label: fig-scatterplot1
#| fig-cap: "Base Plot."
#| fig-alt: "Base Plot."
ggplot2::ggplot(
data = rb_seasonal, # specify data object
aes(
x = age, # specify variable on x-axis
y = rushing_yards)) # specify variable on y-axis
```
### Add Points {#sec-scatterplotAddPoints}
Third, we create a scatterplot using the `geom_point()` function from the `ggplot2` package, as in @fig-scatterplot2:
```{r}
#| label: fig-scatterplot2
#| fig-cap: "Scatterplot."
#| fig-alt: "Scatterplot."
ggplot2::ggplot(
data = rb_seasonal,
aes(
x = age,
y = rushing_yards)) +
geom_point() # add points for scatterplot
```
### Best-Fit Line {#sec-scatterplotBestFitLine}
Fourth, we add a linear best-fit line using the `geom_smooth()`, as in @fig-scatterplot3:
```{r}
#| label: fig-scatterplot3
#| fig-cap: "Scatterplot with Linear Best-Fit Line."
#| fig-alt: "Scatterplot with Linear Best-Fit Line."
ggplot2::ggplot(
data = rb_seasonal,
aes(
x = age,
y = rushing_yards)) +
geom_point() +
geom_smooth(method = "lm") # add linear best-fit line
```
We could also estimate a quadratic polynomial best-fit line, as in @fig-scatterplot4:
```{r}
#| label: fig-scatterplot4
#| fig-cap: "Scatterplot with Quadratic Best-Fit Line."
#| fig-alt: "Scatterplot with Quadratic Best-Fit Line."
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
```
Or, we could estimate a smooth best-fit line using locally estimated scatterplot smoothing (LOESS) to allow for any form of nonlinearity, as in @fig-scatterplot5:
```{r}
#| label: fig-scatterplot5
#| fig-cap: "Scatterplot with Best-Fit Line Using Locally Estimated Scatterplot Smoothing (LOESS)."
#| fig-alt: "Scatterplot with Best-Fit Line Using Locally Estimated Scatterplot Smoothing (LOESS)."
ggplot2::ggplot(
data = rb_seasonal,
aes(
x = age,
y = rushing_yards)) +
geom_point() +
geom_smooth(method = "loess") # add smooth best-fit (LOESS) line
```
By default, the best-fit line is based on a generalized additive model, which allows for nonlinearity, as in @fig-scatterplot6:
```{r}
#| label: fig-scatterplot6
#| fig-cap: "Scatterplot with Best-Fit Line from Generalized Additive Model."
#| fig-alt: "Scatterplot with Best-Fit Line from Generalized Additive Model."
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"
```
### Modify Axes {#sec-scatterplotAxes}
Then, we can change the axes, as in @fig-scatterplot7:
```{r}
#| label: fig-scatterplot7
#| fig-cap: "Scatterplot with Modified Axes."
#| fig-alt: "Scatterplot with Modified Axes."
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
)
```
### Plot Labels {#sec-scatterplotPlotLabels}
Then, we can add plot labels, as in @fig-scatterplot8:
```{r}
#| label: fig-scatterplot8
#| fig-cap: "Scatterplot with Plot Labels."
#| fig-alt: "Scatterplot with Plot Labels."
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)"
)
```
### Theme {#sec-scatterplotTheme}
Then, we can use a theme such as the classic theme (`theme_classic()`) to make it more visually presentable, as in @fig-scatterplot9:
```{r}
#| label: fig-scatterplot9
#| fig-cap: "Scatterplot with Classic Theme."
#| fig-alt: "Scatterplot with Classic Theme."
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
```
Or, we could use a different theme, such as the dark theme (`theme_dark()`) in @fig-scatterplot10.
For a list of themes available in `ggplot2`, see here: <https://ggplot2-book.org/themes#sec-themes>.
```{r}
#| label: fig-scatterplot10
#| fig-cap: "Scatterplot with Dark Theme."
#| fig-alt: "Scatterplot with Dark Theme."
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
```
### Interactive {#sec-scatterplotInteractive}
::: {.content-visible when-format="html:js"}
After creating our plot, we can make the plot interactive using the `ggplotly()` function from the `plotly` package, as in @fig-scatterplot11.
```{r}
#| label: fig-scatterplot11
#| fig-cap: "Interactive Scatterplot Using Plotly."
#| fig-alt: "Interactive Scatterplot Using Plotly."
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)
```
:::
::: {.content-visible when-format="pdf"}
After creating our plot, we can make the plot interactive using the `ggplotly()` function from the `plotly` package.
```{r}
#| eval: false
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)
```
:::
## Line Chart {#sec-lineChart}
A bar plot of Tom Brady's fantasy points by season is depicted in @fig-lineChart.
```{r}
#| label: fig-lineChart
#| fig-cap: "Line Chart."
#| fig-alt: "Line Chart."
ggplot2::ggplot(
data = player_stats_seasonal %>%
filter(player_display_name == "Tom Brady"),
mapping = aes(
x = season,
y = fantasyPoints
)
) +
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
```
### With Highlighting {#sec-lineChartHighlighting}
```{r}
#| label: fig-lineChartHighlighting
#| fig-cap: "Line Chart with Highlighting."
#| fig-alt: "Line Chart with Highlighting."
ggplot2::ggplot(
data = player_stats_seasonal %>%
filter(position_group %in% c("QB")),
mapping = aes(
x = season,
y = fantasyPoints,
group = player_id,
color = player_display_name)
) +
geom_line(linewidth = 2) +
gghighlight::gghighlight(
player_display_name == "Tom Brady",
label_key = player_display_name,
unhighlighted_params = list(linewidth = 0.5)) +
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
```
## Bar Plot {#sec-barPlot}
To create a bar plot, we first compute summary statistics:
```{r}
confidenceLevel <- .95 # for 95% confidence interval
player_stats_seasonal_offense_summary <- player_stats_seasonal %>%
filter(position_group %in% c("QB","RB","WR","TE")) %>%
group_by(position_group) %>%
summarise(
n = sum(!is.na(fantasyPoints)),
mean = mean(fantasyPoints, na.rm = TRUE),
sd = sd(fantasyPoints, 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 @tbl-summaryStats.
```{r}
#| label: tbl-summaryStats
#| tbl-cap: "Table of Summary Statistics."
player_stats_seasonal_offense_summary
```
A bar plot of fantasy points by position is depicted in @fig-barPlot.
```{r}
#| label: fig-barPlot
#| fig-cap: "Bar Plot."
#| fig-alt: "Bar Plot."
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
```
### With Error Bars {#sec-barPlotErrorBars}
Based on the summary statistics in @tbl-summaryStats, we create a bar plot with bars representing the 95% confidence interval in @fig-barPlotConfidenceInterval.
```{r}
#| label: fig-barPlotConfidenceInterval
#| fig-cap: "Bar Plot with Bars Representing the 95% Confidence Interval."
#| fig-alt: "Bar Plot with Bars Representing the 95% Confidence Interval."
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
```
### Modified Color Scheme {#sec-barPlotModifiedColorScheme}
We can also modify the color scheme, as in @fig-barPlotColorScheme
```{r}
#| label: fig-barPlotColorScheme
#| fig-cap: "Bar Plot with Bars Representing the 95% Confidence Interval."
#| fig-alt: "Bar Plot with Bars Representing the 95% Confidence Interval."
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
```
## Faceting {#sec-faceting}
```{r}
#| label: fig-facetedScatterplot
#| fig-cap: "Faceted Scatterplot."
#| fig-alt: "Faceted Scatterplot."
ggplot2::ggplot(
data = player_stats_seasonal %>%
filter(position_group %in% c("QB","RB","WR","TE")),
aes(
x = age,
y = fantasyPoints)) +
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
```
## Examples {#sec-scatterplotExamples}
### Players {#sec-scatterplotPlayers}
#### Running Back Performance By Player Age {#sec-plotRBperformanceByAge}
```{r}
# 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) %>%