-
Notifications
You must be signed in to change notification settings - Fork 0
/
03-exploring-data.qmd
3181 lines (2373 loc) · 115 KB
/
03-exploring-data.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
# Exploring and Transforming Data {#sec-chap03}
```{r}
#| label: setup
#| results: hold
#| include: false
base::source(file = "R/helper.R")
ggplot2::theme_set(ggplot2::theme_bw())
options(show.signif.stars = FALSE)
options(rgl.useNULL = TRUE) # Suppress separate window opened by {rgl}.
```
## Chapter section list {.unnumbered}
::::: {#obj-chap03}
:::: {.my-objectives}
::: {.my-objectives-header}
Table of content (TOC)
:::
::: {.my-objectives-container}
- Examing distribution (@sec-chap03-1)
- Histograms (@sec-chap03-1-1)
- Density estimation (@sec-chap03-1-2)
- Quantile-comparison plots (@sec-chap03-1-3)
- Boxplots (@sec-chap03-1-4)
- Examing relationships (@sec-chap03-2)
- Scatterplots (@sec-chap03-2-1)
- Parallel boxplots (@sec-chap03-2-2)
- More on the plot function (@sec-chap03-2-3)
- Examining multivariate data (@sec-chap03-3)
- Three-dimensional plots (@sec-chap03-3-1)
- Scatterplot Matrices (@sec-chap03-3-2)
- Transforming data (@sec-chap03-4)
- Logarithms (@sec-chap03-4-1)
- Power transformations (@sec-chap03-4-2)
- Transformations and Exploarative Data Analysis (EDA) {@sec-chap03-4-3}
- Transforming resticted-range variables (@sec-chap03-4-4)
- Other transformations (@sec-chap03-4-5)
- Point labelling and identification (@sec-chap03-5)
- The identify() function (@sec-chap03-5-1)
- Automatic point labelling with car::showLabels() (@sec-chap03-5-2)
:::
::::
:::::
## Examing distributions {#sec-chap03-1}
### Histograms {#sec-chap03-1-1}
> The shape of the histogram is determined in part by the number of bins and the location of their boundaries. With too few bins, the histogram can hide interesting features of the data, while with too many bins, the histogram is very rough, displaying spurious features of the data.
The help page for `ggplot2::geom_histogram()` recommends: "You should always override this [default] value, exploring multiple widths to find the best to illustrate the stories in your data."
There are several algorithm to calculate an optimal number of bins depending of the sample size and distribution. Fox/Weisberg mention the rule by Freedman and Diaconis [-@freedman1981a]:
$$
\frac{n^\frac{1}{3}(max-min)}{2(Q_{3}-Q_{1})}
$$ {#eq-chap03-FD}
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap03-histograms}
: Histograms
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### base R
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-default-base-r-histogram}
: Default base R histogram
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-default-base-r-histogram}
```{r}
#| label: default-base-r-histogram
Prestige <- carData::Prestige
base::with(Prestige, graphics::hist(income))
```
Default base R histogram of income in the Canadian occupational-prestige data
:::
::::
:::::
###### FD rule
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-compute-bins-FD}
: Compute number of bins with the Freedman-Diaconis rule [-@freedman1981a]
::::::
:::
::::{.my-r-code-container}
::: {#lst-compute-bins-FD}
```{r}
#| label: compute-bins-FD
Income <- Prestige$income
base::ceiling(
base::length(Income)^(1/3) *
(base::max(Income) - base::min(Income)) /
(2 * (stats::quantile(Income, 0.75)
- stats::quantile(Income, 0.25)))[[1]]
)
```
Compute number of bins of `income` with the Freedman-Diaconis rule [-@freedman1981a]
:::
::::
:::::
###### base R 2
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-fd-base-r-histogram2}
: Base R histogram with `breaks = "FD"`
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-fd-base-r-histogram2}
```{r}
#| label: fd-base-r-histogram2
base::with(Prestige, graphics::hist(income, breaks = "FD"))
```
Base R histogram: Number of bins computed after Freedman and Diaconis [-@freedman1981a]
:::
::::
:::::
###### ggplot2
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-default-ggplot2-histogram}
: Histogram with {**ggplot2**} (30 bins default)
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-default-ggplot2-histogram}
```{r}
#| label: default-ggplot2-histogram
Prestige |>
ggplot2::ggplot(
ggplot2::aes(x = income)
) +
ggplot2::geom_histogram(
fill = "grey",
color = "black"
)
```
Histogram with {**ggplot2**} with default number of bins (30)
:::
::::
:::::
###### ggplot2 2
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-default-ggplot2-histogram2}
: Histogram with {**ggplot2**} with bin number computed after Freedman & Diaconis
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-default-ggplot2-histogram2}
```{r}
#| label: default-ggplot2-histogram2
Prestige |>
ggplot2::ggplot(
ggplot2::aes(x = income)
) +
ggplot2::geom_histogram(
fill = "grey",
color = "black",
bins = grDevices::nclass.FD(Prestige$income)
)
```
Histogram with {**ggplot2**}. Bin number computed after Freedman and Diaconis [-@freedman1981a]
:::
::::
:::::
:::
::::
:::::
A special type of histograms are *stem-and-leaf displays*, which are histograms that encode the numeric data directly in their bars. I do not find them very usefull, because they are different to interpret and do not have essential advantages. They may be helpful for small data sets as a kind of paper-and-pencil method for visualizing.
Stem-and-leaf graphs can be produced with the `graphics::stem()` function or using the `aplpack::stem.leaf()` function.
:::::{.my-resource}
:::{.my-resource-header}
:::::: {#lem-chap03-aplpack}
: Another Plot Package {aplpack}
::::::
:::
::::{.my-resource-container}
##### Functions for drawing some special plots
Besides plotting stem-and-leaf graphs with `aplpack::stem.leaf()` from the {**aplpack**} package, I noticed that there are some other interesting graphic functions in this package, which I should explore.
For instance `aplpack::plotsummary()` is an interesting function that shows important characteristics of the variables of a data set. For each variable a plot is computed consisting of a `r glossary("Bar Charts", "barplot")`, an `r glossary("ecdf")`, a `r glossary("Density Plots", "density trace")` and a `r glossary("Boxplots", "boxplot")`.
See @pak-aplpack.
::::
:::::
### Density Estimation {#sec-chap03-1-2}
*Nonparametric density estimation* often produces a more satisfactory representation of the distribution of a numeric variable than a traditional histogram. Unlike a histogram, a nonparametric density estimate is continuous and so it doesn’t dissect the range of a numeric variable into discrete bins.
`r glossary("Kernel density estimation")` (KDE) is the application of kernel smoothing for probability density estimation. The bandwith controls the degree of smoothness of the density estimate:
The bandwidth of a density estimate is the continuous analog of the bin width of a histogram: If the bandwidth is too large, then the density estimate is smooth but biased as an estimator of the true density, while if the bandwidth is too small, then bias is low but the estimate is too rough and the variance of the estimator is large.
The `adaptiveKernel()` function in the {**car**} package employs an algorithm that uses different bandwidths depending on the local observed density of the data, with smaller bandwidths in dense regions and larger bandwidths in sparse regions.
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap03-density-estimation}
: Density estimation
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### stats::density() 1
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-density1}
: Nonparametric fixed-bandwidth and adaptive-bandwidth kernel density estimates `(adjust = 1)`
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-density1}
```{r}
#| label: density1
with(Prestige, {
hist(
income,
freq = FALSE,
ylim = c(0, 1.5e-4),
breaks = "FD",
main = ""
)
lines(density(income, from = 0), lwd = 3, lty = 2)
lines(car::adaptiveKernel(income, from = 0, adjust = 1),
lwd = 2,
lty = 1) # solid line
rug(income)
legend(
"topright",
c("Fixed bandwidth", "Adaptive bandwidth"),
lty = 2:1, # dashed with proportion 2:1
lwd = 2,
inset = .02
)
box()
})
```
Nonparametric fixed-bandwidth and adaptive-bandwidth kernel density estimates (adjust = 1) for the distribution of income in the `Prestige` data set; a density histogram of income is also shown. The rug-plot at the bottom of the graph shows the location of the income values.
:::
***
The command to draw the graph in @lst-chap03-density1 is relatively complicated and thus requires some explanation:
- The `base::with()` function is used as usual to pass the data frame `Prestige` to the second argument. Here the second argument is a compound expression consisting of all the commands between the initial { and the final }.
- The call to `graphics::hist()` draws a histogram in density scale, so the areas of all the bars in the histogram sum to 1.
- The argument `main=""` suppresses the title for the histogram.
- The `ylim` argument sets the range for the y-axis to be large enough to accommodate the adaptive-kernel density estimate. The value 1.5e-4 is in scientific notation, 1.5 × 10−4 = 0.00015.
- The fixed-bandwidth and adaptive-bandwidth kernel estimates are computed, respectively, by `stats::density()` and `car::adaptiveKernel()`.
- In each case, the result returned by the function is then supplied as an argument to the `graphics::lines()` function to add the density estimate to the graph.
- The argument `from = 0` to both `density()` and `adaptiveKernel()` ensures that the density estimates don’t go below income = 0.
- The call to `graphics::rug()` draws a rug-plot (one-dimensional scatterplot) of the data at the bottom of the graph.
- The remaining two commands add a legend and a frame around the graph.
::::
:::::
Both nonparametric density estimates and the histogram suggest a mode at around $5,000, and all three show that the distribution of income is rightskewed. The fixed-bandwidth kernel estimate has more wiggle at the right where data are sparse, and the histogram is rough in this region, while the adaptive-kernel estimator is able to smooth out the density estimate in the low-density region.
###### stats::density() 2
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-density2}
: Nonparametric fixed-bandwidth and adaptive-bandwidth kernel density estimates `(adjust = 0.5)`
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-density2}
```{r}
#| label: density2
with(Prestige, {
hist(
income,
freq = FALSE,
ylim = c(0, 1.5e-4),
breaks = "FD",
main = ""
)
lines(density(income, from = 0), lwd = 3, lty = 2)
lines(car::adaptiveKernel(income, from = 0, adjust = 0.5),
lwd = 2,
lty = 1) # solid
rug(income)
legend(
"topright",
c("Fixed bandwidth", "Adaptive bandwidth"),
lty = 2:1, # dashed with proportion 2:1
lwd = 2,
inset = .02
)
box()
})
```
Nonparametric fixed-bandwidth and adaptive-bandwidth kernel density estimates (adjust = 0.5) for the distribution of `income` in the `Prestige` data set; a density histogram of `income` is also shown. The rug-plot at the bottom of the graph shows the location of the `income` values.
:::
::::
:::::
###### ggplot2::geom_density()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-density-ggplot2}
: Histogram, rug and smoothed density estimate
::::::
:::
::::{.my-r-code-container}
::: {#lst-density-ggplot2}
```{r}
#| label: density-ggplot2
Prestige |>
ggplot2::ggplot(
ggplot2::aes(x = income)
) +
ggplot2::geom_histogram(
ggplot2::aes(y = ggplot2::after_stat(density)),
color = "black",
fill = "grey",
bins = grDevices::nclass.FD(Prestige$income)
) +
ggplot2::geom_density(
adjust = 1,
kernel = "gaussian",
color = "red",
linewidth = 1
) +
ggplot2::geom_rug()
```
Histogram with a kernel density estimate overlaid, which is a smoothed version of the histogram. The rug-plot at the bottom of the graph shows the location of the `income` values from the `Prestige` dataset.
:::
::::
:::::
::: {.callout-warning #wrn-chap03-adaptive-kernel}
##### Don't know how to inlcude adaptive kernel density estimation
The {**car**} package has with `car::densityPlot()` an additional function, that both computes and draws density estimates with either a fixed or adaptive kernel. I do not know how to include the adaptive kernel density estimation from the {**car**} package to get a full reproduction of book’s Figure 3.3 with {**ggplot2**}.
:::
###### my_hist_dnorm()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-my-hist-dnorm}
: Using my own function to create a histogram with density estimate and overlaid dnorm curve
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-my-hist-dnorm}
```{r}
#| label: my-hist-dnorm
my_hist_dnorm(Prestige, Prestige$income)
```
Histogram with density estimation and overlaid dnorm curve
:::
***
I have my own function `my_hist_dnorm()` adapted by supplying the Freeman-Diaconis rule [-@freedman1981a] as default value for the number of bins.
Additionally I have written with `my_nbins()` another small functions which returns the number of bins according to the Freeman-Diaconis rule.
::::
:::::
:::
::::
:::::
### Quantile-comparison plots {#sec-chap03-1-3}
A *quantile-comparison plot*, or quantile-quantile plot (`r glossary("Q-Q-plot")`), provides an effective graphical means of making the comparison, plotting the ordered data on the vertical axis against the corresponding quantiles of the reference distribution on the horizontal axis. If the data conform to the reference distribution, then the points in the quantile-comparison plot should fall close to a straight line, within sampling error.
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap03-qq-plots}
: Quantile-quantile plots
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### stats::qqnorm()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-stats-qqnorm}
: Base R: Quantile-Quantile Plot
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-stats-qqnorm}
```{r}
#| label: stats-qqnorm
stats::qqnorm(Prestige$income,
ylab = "Income")
stats::qqline(Prestige$income)
```
Normal quantile-comparison plot for `income` from the `Prestige` dataset.
:::
***
Many points, especially at the right of the graph, are far from the line of the theoretical quantiles. We have therefore evidence that the distribution of `income` is not like a sample from a normal population.
::::
:::::
###### car::qqPlot()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-car-qqplot}
: car: Quantile-quantile plot
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-car-qqplot}
```{r}
#| label: car-qqplot
car::qqPlot( ~ income, data = Prestige, id = list(n = 3))
```
Normal quantile-comparison plot for `income.`
:::
***
The broken lines give a pointwise 95% confidence envelope around the fitted solid line. Three points were labeled automatically. Because many points, especially at the right of the graph, are outside the confidence bounds, we have evidence that the distribution of `income` is not like a sample from a normal population.
::::
:::::
The function `car::qqPLot()` has several advantages:
1) It produces a pointwise 95% confidence envelope around the fitted solid line.
2) It labels the most extreme data points.
3) The `car::qqPlot()` function can be used to plot the data against *any* reference distribution.
###### my_qq_plot()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-my-qq-plot}
: Q-Q-plot using my own function applying {**ggplot2**}
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-my-qq-plot}
```{r}
#| label: my-qq-plot
my_qq_plot(Prestige, Prestige$income)
```
Q-Q-plot: Comparing data points against a normal distribution
:::
***
My own function lacks the confidence interval cannot label the most extreme points. I have to think if and how I could add these features to `my_qq_plot()`.
::::
:::::
###### chi-square
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-chi-square-illustration}
: car::qqPlot: Chi-square illustration
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-chi-square-illustration}
```{r}
#| label: chi-square-illustration
base::set.seed(124) # for reproducibility
car::qqPlot(
rchisq(100, 3),
distribution = "chisq", df = 3,
id = FALSE)
```
Quantile-comparison plot of a sample of size n = 100 from the $χ^2(3)$ distribution against the distribution from which the sample was drawn.
:::
***
The argument `df = 3` to `car::qqPlot()` is passed by it to the `stats::dchisq()` and `stats::qchisq()` functions. The points should, and do, closely match the straight line on the graph, with the fit a bit worse for the larger values in the sample. The confidence envelope suggests that these deviations for large values are to be expected, as they reflect the greater variability of sampled values in the long right tail of the $X^2(3)$ density function.
::::
:::::
:::
::::
:::::
The `car::qqPlot()` function can be used to plot the data against any reference distribution for which there are `r glossary("quantile")` and density function in R. You have simply to specify the root word for the distribution. For example, the root for the normal distribution is "norm", with density function `stats::dnorm()` and quantile function `stats::qnorm()`. See also [chapter 8](https://rstudio.github.io/r-manuals/r-intro/Probability-distributions.html) of the the Quarto manual of [An Introduction to R](https://rstudio.github.io/r-manuals/r-intro/). [@rcoreteam2024]
![Probability functions in R](img/chap03-r-probability-functions.png){#fig-03-1
fig-alt='List of probability functions in R as a two part table with five columns: It shows the name of the "Distribution" (column 1), such as "normal" or "chi-square", the "Design or Mass Function" (column 2), such as "dnorm(x, mean = 0, sd = 1)" or "qchisq(n, df)", the "Quantile Function" (column 3), such as "qnorm(p, mean = 0, sd = 1)" the "Distribution Function" column 4), such as "pnorm(q, mean = 0, sd = 1)" or "pchisq(q, df)" and the "Random Number Function" (column 5), such as "rnorm(n, mean = 0, sd = 1)" or "rchisq(n, df)"' fig-align="center"
width="70%"}
An illustration is shown with @lst-chap03-chi-square-illustration: The `rchisq()` function is used to generate a random sample from the chi-square distribution with three df (`r glossary("degrees of freedom")`) and then plotted the sample against the distribution from which it was drawn.
### Boxplots {#sec-chap03-1-4}
Although boxplots are most commonly used to compare distributions among groups, they can also be drawn to summarize the distribution of a numeric variable in a single sample, providing a quick check of symmetry and the presence of outliers.
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap03-boxplot}
: Boxplots
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### graphics::boxplot
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-boxplot-base-r}
: graphics::boxplot(): Boxplot of income
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-boxplot-base-r}
```{r}
#| label: boxplot-base-r
graphics::boxplot(Prestige$income)
```
Boxplot of income, plotted with base R `graphics::boxplot()`
:::
::::
:::::
###### car::Boxplot
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-boxplot-car}
: car::Boxplot(): Boxplot of income
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-boxplot-car}
```{r}
#| label: boxplot-car
car::Boxplot(~ income, data = Prestige)
```
Boxplot of income, plotted with `car::Boxplot()`. Several outlying cases were labeled automatically.
:::
***
`car::Boxplot()` adds automatic identification of outlying values (by default, up to 10), points that are shown individually in the boxplot. Points identified as outliers are those beyond the *inner* fences, which are 1.5 times the interquartile range below the first quartile and above the third quartile.
The names shown in the output are the cases that are labeled on the graph and are drawn from the row names of the `Prestige` data set.
::::
:::::
:::
::::
:::::
The `ggplot2::geom_boxplot()` draws boxplots but has no options to label the outliers. To reproduce Figure 3.6 I need to add some code to the compute the outliers and label them with {**ggrepel**}.
:::::{.my-experiment}
:::{.my-experiment-header}
:::::: {#def-chap03-boxplot-outlier-labelled}
: {ggplot2} boxplot with outlier labelled
::::::
:::
::::{.my-experiment-container}
::: {.panel-tabset}
###### default
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-boxplot-ggplot2}
: Boxplot of income (default)
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-boxplot-ggplot2}
```{r}
#| label: boxplot-ggplot2
Prestige <- carData::Prestige
Prestige |>
ggplot2::ggplot(
ggplot2::aes(y = income)
) +
ggplot2::geom_boxplot()
```
Boxplot of income, plotted with `ggplot2::geom_boxplot()`
:::
::::
:::::
###### outliers
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-compute-boxplot-outliers}
: Boxplot of income with outliers labelled
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-compute-boxplot-outliers}
```{r}
#| label: compute-boxplot-outliers
my_find_boxplot_outlier <- function(x) {
return(x < quantile(x, .25) - 1.5*IQR(x) | x > quantile(x, .75) + 1.5*IQR(x))
}
prestige1 <- Prestige |>
dplyr::mutate(outlier = my_find_boxplot_outlier(income)) |>
tibble::rownames_to_column(var = "ID") |>
dplyr::mutate(outlier =
dplyr::case_when(outlier == TRUE ~ ID,
outlier == FALSE ~ "")
)
set.seed(42)
prestige1 |>
ggplot2::ggplot(
ggplot2::aes(y = income)
) +
ggrepel::geom_text_repel(
ggplot2::aes(
x = 0,
label = outlier
),
nudge_x = 0.05,
direction = "y",
hjust = 0,
) +
ggplot2::geom_boxplot()
```
Boxplot of income with outliers labelled plotted with `ggplot2::geom_boxplot()` and using `ggrepel::geom_text_repel()`
:::
::::
:::::
:::
::::
:::::
***
## Examing relationships {#sec-chap03-2}
### Scatterplots {#sec-chap03-2-1}
Understanding and using scatterplots is at the heart of regression analysis!
`r glossary("Scatterplot", "Scatterplots")` are useful for studying the mean and variance functions in the regression of the y-variable on the x-variable. In addition, scatterplots can help identify `r glossary("outliers")`, points that have values of the response far different from the expected value, and `r glossary("leverage")` points, cases with extremely large or small values on the x-axis.
:::::{.my-example}
:::{.my-example-header}
:::::: {#exm-chap03-scatterplot}
: Scatterplots
::::::
:::
::::{.my-example-container}
::: {.panel-tabset}
###### graphics::plot()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-scatterplot-base-r}
: Simple scatterplot using base R `graphics::plot()` function
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-scatterplot-base-r}
```{r}
#| label: scatterplot-base-r
graphics::plot(prestige ~ income, data = Prestige)
```
Scatterplot of `prestige` versus `income` for the Canadian occupational-prestige data
:::
***
The scatterplot in @lst-chap03-scatterplot-base-r is a *summary graph* for the regression problem in which `prestige` is the response and `income` is the predictor. As our eye moves from left to right across the graph, we see how the distribution of `prestige` changes as `income` increases. In technical terms, we are visualizing the *conditional distributions* of `prestige` given the value of `income`.
::::
:::::
The overall story here is that as `income` increases, so does `prestige`, at least up to about $10,000, after which the value of `prestige` stays more or less fixed on average at about 80.
###### car::scatterplot
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-scatterplot-car}
: Enhanced scatterplot with `car::scatterplot()`
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-scatterplot-car}
```{r}
#| label: scatterplot-car
car::scatterplot(
prestige ~ income,
data = Prestige,
id = list(n = 4)
)
```
Enhanced scatterplot of prestige versus income produced by the `car::scatterplot()` function. Four points were identified using the `id` argument.
:::
***
- **Points** correspond to the pairs of (`income`, `prestige`) values in the Prestige data frame, which is supplied in the data argument.
- **The thick solid straight line** in the scatterplot is the simple linear regression of `prestige` on `income` fit by ordinary least squares (`r glossary("OLS")`).
- **The dashed line** is fit using a nonparametric *scatterplot smoother*, and it provides an estimate of the mean function that does not depend on a parametric regression model, linear or otherwise.
- **The two dash-dotted lines** provide a nonparametric estimate of the square root of the variance function (i.e., the conditional standard deviation of the response), based on separately smoothing the positive and negative residuals from the fitted *nonparametric* mean function.
- Also shown on each axis are **marginal boxplots** of the plotted variables, summarizing the univariate distributions of x and y.
- The only optional argument is `id=list (n=4)`, to identify by row name the four **most extreme cases**, where by default “extreme” means farthest from the point of means using Mahalanobis distances.
All these features, and a few others that are turned off by default, can be modified by the user, including the color, size, and symbol for points; the color, thickness, and type for lines; and inclusion or exclusion of the least-squares fit, the mean smooth, variance smooth, and marginal boxplots. See help ("scatterplot") for the available options.
::::
:::::
In @lst-chap03-scatterplot-car the least squares line cannot match the obvious curve in the mean function that is apparent in the smooth fit. So modeling the relationship of `prestige` to `income` by simple linear regression is likely to be inappropriate.
:::::{.my-resource}
:::{.my-resource-header}
:::::: {#lem-resource-text}
: Nonparametric regression as an appendix to the R Companion
::::::
:::
::::{.my-resource-container}
@lst-chap03-scatterplot-car uses as an plot enhancement in the {**car**} package a smoother, designed to help us extract information from a graph.
*Nonparametric regression*, in which smoothers are substituted for more traditional regression models, is described in an [online appendix to the R Companion](https://www.john-fox.ca/Companion/appendices/Appendix-Nonparametric-Regression.pdf).
::::
:::::
###### ggplot2::geom_point()
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-scatterplot-ggplot2}
: Scatterplot with `ggplot2::geom_point()`
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-scatterplot-ggplot2}
```{r}
#| label: scatterplot-ggplot2
#| results: hold
gg_Prestige <- carData::Prestige |>
ggplot2::ggplot(
ggplot2::aes(
x = income,
y = prestige
)
) +
ggplot2::geom_point(
shape = "circle open",
size = 2
) +
ggplot2::stat_smooth(
formula = 'y ~ x',
method = "loess",
span = .75,
level = 0.95
) +
ggplot2::stat_smooth(
formula = 'y ~ x',
method = "lm",
se = FALSE
) +
ggplot2::coord_cartesian(
xlim = c(0, 26000),
ylim = c(10, 90),
expand = TRUE,
default = FALSE,
clip = "on"
)
save_data_file("chap03", gg_Prestige, "gg_Prestige.rds")
gg_Prestige
```
Scatterplot of `prestige` versus `income` produced by different functions of the {**ggplot2**} package.
:::
***
The default smoother employed by `ggplot2::geom_smooth()` depends on the size of the largest group. `stats::loess()` would have been used here because we have less than 1,000 observation. But I have applied the `loess() `function explicitly to prevent a warning message.
The span in loess is the fraction of the data used to determine the fitted value of y at each x. A larger span therefore produces a smoother result, and too small a span produces a fitted curve with too much wiggle. The trick is to select the smallest span that produces a sufficiently smooth regression mean function. The default span of 2/3 works well most of the time but not always
::::
:::::
Besides the labelled points and the marginal boxplots, I could not create smoother with the similar width as in the {**car**} example. I assume it has to do with "the *nonparametric estimate* of the square root of the variance function (i.e., the conditional standard deviation of the response), based on separately smoothing the positive and negative residuals from the fitted nonparametric mean function. "
###### categorical
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-scatterplot-car-categorical}
: Conditioning on a categorical variable
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-scatterplot-car-categorical}
```{r}
#| label: scatterplot-car-categorical
Prestige$type <- factor(Prestige$type, levels = c("bc", "wc", "prof"))
car::scatterplot(
prestige ~ income | type,
data = Prestige,
legend = list(coords = "bottomright", inset = 0.1),
smooth = list(span = 0.9),
col = ggokabeito::palette_okabe_ito(c(1, 3, 5))
)
xtabs( ~ type, data = Prestige)
glue::glue(" ")
glue::glue("bc = blue color, wc = white color, prof = professional")
```
Scatterplot of `prestige` versus `income`, coded with {**car**} by `type` of occupation. The span of the loess smoother is set to 0.9.
:::
***
- **The variables** for the coded scatterplot are given in a formula as `y ~ x | g`, which is interpreted as plotting y on the vertical axis, x on the horizontal axis, and marking points according to the value of g (or “y versus x given g”).
- **The legend** for the graph, automatically generated by the scatterplot () function, is placed by default above the plot; we specify the legend argument to move the legend to the lower-right corner of the graph.
- We select a **larger span**, span=0.9, for the scatterplot smoothers than the default (span=2/3) because of the small numbers of cases in the occupational groups.
- As **color palette** I used the colorblind friendly Okabe Ito scale from {**ggokabeito**} instead of the default colors from {**car**} .
The default smoother employed by `car::scatterplot()` is the loess smoother. The span in loess is the fraction of the data used to determine the fitted value of y at each x. A larger span therefore produces a smoother result, and too small a span produces a fitted curve with too much wiggle. The trick is to select the smallest span that produces a sufficiently smooth regression mean function. The default span in {**car**} of 2/3 works well most of the time but not always. (In {**ggplot2**} the default span is 3/4.)
::::
:::::
The nonlinear relationship in @lst-chap03-scatterplot-car has disappeared, and we now have three reasonably linear regressions with different slopes. The slope of the relationship between `prestige` and `income` looks steepest for blue-collar occupations and least steep for professional and managerial occupations.
###### categorical2
:::::{.my-r-code}
:::{.my-r-code-header}
:::::: {#cnj-chap03-scatterplot-ggplot2-categorical}
: Numbered R Code Title
::::::
:::
::::{.my-r-code-container}
::: {#lst-chap03-scatterplot-ggplot2-categorical}
```{r}