-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path03-data-visualisation.Rmd
826 lines (598 loc) · 26.9 KB
/
03-data-visualisation.Rmd
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
---
title: "Data visualization"
description: |
R for Data Science Book
author:
- name: Alexis Solis Cancino
url: https://www.linkedin.com/in/asolisc/
# affiliation: Spacely Sprockets
# affiliation_url: https://example.com/spacelysprokets
date: "`r Sys.Date()`"
output:
distill::distill_article:
toc: true
toc_float: true
css: "styles.css"
editor_options:
chunk_output_type: console
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(
echo = TRUE,
message = FALSE,
warning = FALSE,
layout = "l-body-outset")
source("D:/01-Data-Science/03-Helper-Scripts/ggplot2_themes.R")
# file.show("D:/01-Data-Science/03-Helper-Scripts/ggplot2_themes.R")
library(ggplot2)
options(ggplot2.continuous.colour="viridis")
options(ggplot2.continuous.fill="viridis")
```
# 1. Introduction
The `ggplot2` package is one of the most versatile frameworks for data visualization. It implements the **grammar of graphics** - a system for describing and building graphs by using *layers*. This package is one of the 8 *core-tidyverse* packages.
# 2. First Steps
We first start by loading the `tidyverse` meta-package:
```{r}
library(tidyverse)
```
Then, we can use the `mpg` tibble, a dataset included in the `ggplot2` package. `mpg` contains observations collected by the US Environmental Protection Agency on 38 models of car.
```{r}
mpg
```
```{r, layout = "l-body-outset", fig.asp=0.618}
mpg %>%
mutate(cyl = as_factor(cyl)) %>%
ggplot(mapping = aes(x = displ, y = hwy, colour = cyl)) +
geom_point() +
scale_colour_manual(values = amazing_colors)
```
# 3. Aesthetic Mappings
You can add a third variable, like class, to a two dimensional scatterplot by mapping it to an aesthetic. An aesthetic is a visual property of the objects in your plot.
Since we already use the word "value" to describe data, let's use the word "level" to describe aesthetic properties.
```{r}
mpg %>%
ggplot() +
geom_point(mapping = aes(x = displ, y = hwy, color = class))
```
To map an aesthetic to a variable, associate the name of the aesthetic to the name of the variable inside `aes()`. ggplot2 will automatically assign a unique level of the aesthetic (here a unique color) to each unique value of the variable, a process known as scaling.
```{r}
mpg %>%
ggplot() +
geom_point(mapping = aes(x = displ,
y = hwy,
size = class,
colour = class))
```
We could also use the `alpha` or `shape` aesthetic:
```{r}
mpg %>%
ggplot() +
geom_point(aes(x = displ,
y = hwy,
alpha = class))
```
```{r}
mpg %>%
ggplot(aes(x = displ, y = hwy)) +
geom_point(aes(shape = class))
```
What happened to the SUVs? ggplot2 will only use six shapes at a time. By default, additional groups will go unplotted when you use the shape aesthetic.
It selects a reasonable scale to use with the aesthetic, and it constructs a legend that explains the mapping between levels and values. For x and y aesthetics, ggplot2 does not create a legend, but it creates an axis line with tick marks and a label. The axis line acts as a legend; it explains the mapping between locations and values.
You can also set the aesthetic properties of your geom manually. For example, we can make all of the points in our plot blue:
```{r}
mpg %>%
ggplot() +
geom_point(mapping = aes(x = displ, y = hwy),
colour = "dark green")
```
To set an aesthetic manually, set the aesthetic by name as an argument of your geom function; i.e. it goes outside of `aes()`.
## 3.1 Exercises
1. What's gone wrong with this code? Why are the points not blue?
```{r}
mpg %>%
ggplot() +
geom_point(mapping = aes(x = displ,
y = hwy,
color = "blue"))
```
The color should be set outside the `aes()` function, i.e. as an argument to the `geom()` function.
2. Which variables in mpg are categorical? Which variables are continuous? (Hint: type ?mpg to read the documentation for the dataset). How can you see this information when you run `mpg`?
```{r, eval=FALSE}
# Not run
help(mpg)
```
```{r}
mpg %>% glimpse()
```
The categorical variables are:
- `manufacturer`
- `model`
- `trans`
- `drv`
- `fl`
- `class`
The numeric variables are:
- `model`
- `year`
- `cyl`
- `cty`
- `hwy`
3. Map a continuous variable to `color`, `size`, and `shape`. How do these aesthetics behave differently for categorical vs. continuous variables?
```{r}
mpg %>%
ggplot() +
geom_point(aes(x = displ, y = hwy, color = year))
```
```{r}
mpg %>%
ggplot() +
geom_point(aes(x = displ, y = hwy, size = year))
```
```{r, eval = F}
mpg %>%
ggplot() +
geom_point(aes(x = displ, y = hwy, shape = year))
```
The `color`, `shape`, and `size` aesthetics work better with categorical variables. `shape` levels cannot be mapped to a continuous variable.
4. What happens if you map the same variable to multiple aesthetics?
```{r}
mpg %>%
ggplot() +
geom_point(aes(x = displ,
y = hwy,
color = class,
alpha = class))
```
`ggplot2` maps them all accordingly.
5. What does the stroke aesthetic do? What shapes does it work with? (Hint: use `?geom_point`).
```{r}
mpg %>%
ggplot() +
geom_point(aes(x = displ,
y = hwy,
color = class),
stroke = 2,
shape = 11)
```
`stroke` changes the border's width of certain shapes. For example, shapes 11 and 21 work with stroke. `stroke` is not available for all `geom()` functions.
6. What happens if you map an aesthetic to something other than a variable name, like `aes(colour = displ < 5)`? Note, you'll also need to specify `x` and `y`.
```{r}
mpg %>%
ggplot() +
geom_point(mapping = aes(x = displ,
y = hwy,
colour = displ < 5))
```
## 4. Common Problems
One common problem when creating ggplot2 graphics is to put the `+` in the wrong place: it has to come at the end of the line, not the start. So, for example, the following code is wrong:
```{r wrong-code, eval = FALSE}
ggplot(data = mpg)
+ geom_point(mapping = aes(x = displ, y = hwy))
```
## 5. Facets
Another way to add additional variables, particularly useful for categorical variables, is to split your plot into **facets**: subplots that each display one subset of the data.
### Facet by One Variable
To facet your plot by a single variable, use `facet_wrap()`. The first argument of `facet_wrap()` should be a formula created with `~` followed by a variable name. The variable that you pass to `facet_wrap()` *should be discrete*.
```{r}
mpg %>%
ggplot() +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow = 2)
```
### Facet by Two Variables
To facet your plot on the combination of two variables, add `facet_grid()` to your plot call. The first argument of `facet_grid()` is also a formula. This time the formula should contain two variable names separated by a `~`. For example: `x ~ y`. We can facet the `mpg` dataset by `drv` and `cyl`:
```{r}
mpg %>%
ggplot() +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ cyl)
```
### Facet: Rows Only
If you prefer to not facet in the rows or columns dimension, use a `.` instead of a variable name. Thus, to facet by rows only use: `+ facet_grid(var1 ~ .)`.
```{r}
mpg %>%
ggplot() +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(cyl ~ .)
```
### Facet: Columns Only
To facet by columns only use: `+ facet_grid(. ~ var1)`.
```{r}
mpg %>%
ggplot() +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(. ~ cyl)
```
## 5.1 Exercises
1. What happens if you facet on a continuous variable?
```{r}
mpg %>%
ggplot(aes(x = displ, y = hwy)) +
geom_point() +
facet_grid(year ~ cty)
```
It either displays too many facets or groups them. This happens because the continuous variable is converted to categorical.
2. What do the empty cells in plot with `facet_grid(drv ~ cyl)` mean? How do they relate to this plot?
```{r}
mpg %>%
ggplot(aes(displ, hwy)) +
geom_point() +
facet_grid(drv ~ cyl)
```
Empty cells mean that there's no data that meets the criteria for that specific facet. In this example, it means that there are no 4- and 5-cylinder cars with rear-wheel-drive.
3. What plots does the following code make? What does `.` do?
```{r}
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(drv ~ .)
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_grid(. ~ cyl)
```
It plots the data into facets according to the variable `drv` and `cyl`, respectively. The `.` argument inside `facet_grid` indicates you're faceting by only one variable.
4. Take the first faceted plot in this section:
```{r}
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow = 2)
```
What are the advantages to using faceting instead of the color aesthetic? What are the disadvantages? How might the balance change if you had a larger dataset?
Faceting actually divides the data into panels, so the separation of the categorical variable is more visual and clear. On the other hand, if the *factor* (categorical) variable had too many different categories, faceting wouldn't be feasible, since we would have too many panels and it's no longer practical to visualize. That's were the `color` aesthetic could work a little bit better.
5. Read `?facet_wrap`. What does `nrow` do? What does `ncol` do? What other options control the layout of the individual panels? Why doesn't facet\_grid() have `nrow` and `ncol` arguments?
```{r}
ggplot(data = mpg) +
geom_point(mapping = aes(x = displ, y = hwy)) +
facet_wrap(~ class, nrow = 2, dir = "v")
```
The `nrow` and `ncol` arguments are unnecessary for `facet_grid()` since the number of unique values of the variables specified in the function determines the number of rows and columns.
6. When using `facet_grid()` you should usually put the variable with more unique levels in the columns. Why?
There will be more space for columns if the plot is laid out horizontally (landscape).
## 6. Geometric Objects
In ggplot2 syntax, there exist different **geoms**. A **geom** is the geometrical object that a plot uses to represent data. To use *geoms* you'll have to use a family of functions specified by: `geom_*()`.
For example, bar charts use `geom_bar`, line charts use `geom_line()`, boxplots use `geom_boxplot()`, and so on. Scatterplots break the trend, as they are called by using the `geom_point()` *geom*. Below are a couple of examples:
```{r}
mpg %>%
ggplot(mapping = aes(x = displ)) +
geom_boxplot(
fill = amazing_colors[10]) +
scale_y_continuous(
limits = c(-2.5,2.5)
) +
labs(
title = "Just a boxplot geom"
)
```
```{r}
mpg %>%
ggplot(mapping = aes(x = displ)) +
geom_bar(fill = amazing_colors[8]) +
labs(
title = "This is a geom_bar() plot"
)
```
Every geom function in ggplot2 takes a `mapping` argument. However, not every aesthetic works with every geom. You could set the shape of a point, but you couldn't set the "shape" of a line. On the other hand, you *could* set the `linetype` of a line. An interesting example is the `geom_smooth()` geom, which will assign a different `linetype` and a different line for each unique value of the variable that you're mapping to it.
```{r}
mpg %>%
ggplot() +
geom_smooth(
# Map the aesthetics
mapping = aes(x = displ,
y = hwy,
linetype = drv,
color = drv),
# Omit the confidence interval
se = FALSE) +
scale_color_manual(values = amazing_colors)
```
To better understand what `geom_smooth()` is doing, we can overlay the line on top of the raw data and color everything according to `drv`.
```{r}
mpg %>%
# Setting "global" aesthetics
ggplot(aes(x = displ, y = hwy, color = drv)) +
# scatterplot geom goes first
geom_point() +
# geom_smooth goes "on top" of scatterplot
geom_smooth(se = FALSE) +
# Choosing the colors manually
scale_color_manual(values = amazing_colors)
```
### Cheatsheet
`ggplot2` provides over 40 geoms, and [extension packages](https://exts.ggplot2.tidyverse.org/gallery/) provide even more. The best way to get a comprehensive overview is the [`ggplot2` cheatsheet](%5Bhttps://rstudio.com/resources/%5D(https://rstudio.com/resources/cheatsheets/)).
### The `group` aesthetic
Most *geoms* use a single geometric object (e.g. a line) to display multiple rows of data. If you'd like to display **several objects** to map categorical variables to the geometric objects, you can use the `group` aesthetic.
Actually, `ggplot2` will use the `group` aesthetic when you map categorical variables to any aesthetic, but the convenient feature of `group` is that it doesn't add a legend or distinguish features to the *geoms*.
For example, see the difference between the following plots:
```{r}
library(cowplot)
plot1 <- mpg %>%
ggplot() +
geom_smooth(mapping = aes(x = displ, y = hwy, group = drv),
se = FALSE) +
scale_color_manual(values = amazing_colors)
plot2 <- mpg %>%
ggplot() +
geom_smooth(mapping = aes(x = displ, y = hwy, colour = drv),
se = FALSE) +
theme(legend.position = "bottom") +
scale_color_manual(values = amazing_colors)
cowplot::plot_grid(plot1, plot2, nrow = 2)
```
### Legend display with `show.legend`
If we'd like to delete the legend for the second plot, we can actually add `show.legend = FALSE`:
```{r}
mpg %>%
ggplot() +
geom_smooth(mapping = aes(x = displ, y = hwy, colour = drv),
se = FALSE,
show.legend = FALSE)
```
### Multiple geoms
To add multiple *geoms* in the same plot, simply add multiple `geom_*()` functions to `ggplot()`:
```{r}
mpg %>%
ggplot() +
geom_point(mapping = aes(x = displ, y = hwy),
colour = amazing_colors[3]) +
geom_smooth(mapping = aes(x = displ, y = hwy),
colour = amazing_colors[2])
```
### Setting *global* mappings
The code above involved some repetition on the variable mapping. If you wanted to change the mapping, say, of the *y-axis variable*, then it you'd have to change it in both `geom_*()` functions. To avoid this, you can set a global mapping by setting the `mapping = aes()` function inside the `ggplot()` call:
```{r}
mpg %>%
ggplot(mapping = aes(x = displ, y = hwy)) +
geom_point(colour = amazing_colors[5]) +
geom_smooth(colour = amazing_colors[4])
```
### Local mappings
Placing a mapping inside a `geom_*()` function will treat it as a local mapping for that layer. It will overwrite the global mappings set *for that layer only*. This makes it possible to display different aesthetics in different layers:
```{r}
mpg %>%
ggplot(mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(colour = class)) +
geom_smooth() +
scale_colour_manual(values = amazing_colors)
```
### Local Data
You can use the same idea to display *different data on each geom or layer.* In the example below, the smooth line display just a subset of the `mpg` dataset. The *local* `data` argument in `geom_smooth()` overrides the global data argument in `ggplot()` for that layer only:
```{r}
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point(mapping = aes(colour = class)) +
geom_smooth(
# Filter the data for "suv" class
data = mpg %>% filter(class == "suv"),
se = FALSE,
color = amazing_colors[4]
) +
scale_colour_manual(values = amazing_colors)
```
## 6.1 Exercises
1. What geom would you use to draw a line chart? A boxplot? A histogram? An area chart?
For the line chart, you would use `geom_line()`:
```{r}
tidyquant::FANG %>%
filter(symbol == "FB") %>%
ggplot(mapping = aes(x = date, y = close)) +
geom_line(color = amazing_colors[3])
```
For the boxplot, you would use `geom_boxplot()`:
```{r}
tidyquant::FANG %>%
ggplot(mapping = aes(x = symbol, y = close)) +
geom_boxplot(aes(fill = symbol)) +
scale_fill_manual(values = amazing_colors[2:6])
```
For a histogram, you would use `geom_histogram()`:
```{r}
tidyquant::FANG %>%
filter(symbol == "AMZN") %>%
ggplot(mapping = aes(x = close)) +
geom_histogram(fill = amazing_colors[3],
colour = amazing_colors[1],
bins = 15)
```
For an area chart, you would use `geom_area()`:
```{r}
tidyquant::FANG %>%
filter(symbol == "AMZN") %>%
ggplot(mapping = aes(x = date, y = close)) +
geom_area(fill = amazing_colors[5])
```
2. Run this code in your head and predict what the output will look like. Then, run the code in R and check your predictions.
```{r}
ggplot(data = mpg, mapping = aes(x = displ, y = hwy, color = drv)) +
geom_point() +
geom_smooth(se = FALSE)
```
3. What does `show.legend = FALSE` do? What happens if you remove it? Why do you think I used it earlier in the chapter?
It removes the legend that is produced by a certain `geom_*()` function.
4. What does the `se` argument to `geom_smooth()` do?
The documentation says that it is used to choose if the *confidence interval* should be computed and displayed (or not, when it's set to `FALSE`).
5. Will these two graphs look different? Why/why not?
```{r, eval = FALSE}
ggplot(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_point() +
geom_smooth()
ggplot() +
geom_point(data = mpg, mapping = aes(x = displ, y = hwy)) +
geom_smooth(data = mpg, mapping = aes(x = displ, y = hwy))
```
No they won't they have the exact same mappings and data. The only difference is that the first code uses *global* data and mappings, while the second chunk uses *local* data and mappings.
6. Recreate some graphs:
```{r}
mpg %>%
ggplot(mapping = aes(x = displ, hwy)) +
geom_point() +
geom_smooth(se = FALSE)
```
```{r}
mpg %>%
ggplot(mapping = aes(x = displ, hwy)) +
geom_point() +
geom_smooth(mapping = aes(group = drv),
se = FALSE)
```
```{r}
mpg %>%
# Color is mapped in both geoms, so we can set it globally
ggplot(mapping = aes(x = displ, y = hwy, colour = drv)) +
geom_point() +
geom_smooth(se = FALSE) +
scale_color_manual(values = amazing_colors)
```
```{r}
mpg %>%
ggplot(mapping = aes(x = displ, y = hwy)) +
# Color is only mapped in the geom_point() geom
geom_point(mapping = aes(colour = drv)) +
geom_smooth(se = FALSE) +
scale_color_manual(values = amazing_colors)
```
```{r}
mpg %>%
ggplot(mapping = aes(x = displ, y = hwy)) +
geom_smooth(mapping = aes(linetype = drv),
se = FALSE) +
geom_point(mapping = aes(colour = drv)) +
scale_color_manual(values = amazing_colors[2:4])
```
```{r}
mpg %>%
ggplot(mapping = aes(x = displ, y = hwy, colour = drv)) +
# The trick is to use two geom_point() geoms
geom_point(colour = "white", size = 5) +
geom_point() +
scale_color_manual(values = amazing_colors[2:4]) +
theme(
plot.background = element_rect(fill = "#F4F3EE")
)
panel.background = element_line(colour = "#F4F3EE")
```
## 7.Statistical Transformations
For this section, the `diamonds` dataset that comes in `ggplot2` is used. It contains information about \~54,000 diamonds, including the `price`, `carat`, `color`, `clarity`, and `cut` of each diamond.
On the following chart, the *x-axis* displays `cut` while the *y-axis* displays the `count` variable. However, the `count` variable **is not present in the data**.
```{r}
diamonds %>%
ggplot() +
geom_bar(mapping = aes(x = cut))
```
Where does count come from? Many graphs -- like scatterplots -- plot the raw values of your dataset. Other graphs, like bar charts, calculate new values to plot:
- bar charts, histograms, and frequency polygons bin your data and then plot bin counts, the number of points that fall in each bin.
- smoothers fit a model to your data and then plot predictions from the model.
- boxplots compute a robust summary of the distribution and then display a specially formatted box.
## 7.1 What is a *stat*
The algorithm that these plots use to calculate new values from existing data is called a **stat** -- which is short for *statistical transformations*. A *stat* is a function that **builds new variables to be plotted**.
### Which stat is used
You can learn which stat a geom uses by inspecting the default value for the `stat` argument. For example, `?geom_bar` shows that the default value for `stat` is `stat = "count"`, which means that `geom_bar()` uses `stat_count()`. The documentation for `?geom_bar` also shows a section for *Computed variables* which details the variables that are computed by the `stat_count()` function -- in this case, `count` and `prop`.
### Using geoms or stats
You can *generally* use *geoms* and *stats* **interchangeably**. For example, you can recreate the above chart with a `stat_count()` call:
```{r}
diamonds %>%
ggplot() +
stat_count(mapping = aes(x = cut))
```
This works because every geom has a default stat; and every stat has a default geom. This means that you can typically use geoms without worrying about the underlying statistical transformation. There are three reasons you might need to use a *stat* explicitly:
1. **Overriding the default stat**: using a different-than-default *stat* could be useful because it allows you to map a different metrics to the *y-axis*. For example, one can change the default `stat_count` in a `geom_bar()` *geom* and use the `stat_identity()` *stat* to map the *y-axis* height to the values of a *y-variable* specified in the `aes()` function. You may want to do this if you had other kind of *frequencies* already present in your data. For example:
```{r}
tribble(
~cut, ~freq,
"Fair", 1610,
"Good", 4906,
"Very Good", 12082,
"Premium", 13791,
"Ideal", 21551
) %>%
# Create a relative frequency column
mutate(rel_freq = freq / sum(freq)) %>%
ggplot(mapping = aes(x = cut, y = rel_freq)) +
# Map the y-axis to the rel_freq column
geom_bar(stat = "identity")
```
2. **Using *stats* as *aesthetics***: it could be useful to map certain *stats* to the `aes()` function. You could choose between the *Computed variables* section in the *help* section. The following is a nifty, little trick to plot a relative frequency plot:
```{r}
diamonds %>%
ggplot() +
geom_bar(
mapping = aes(x = cut,
# We map the stat "groupwise proportion" to the y-axis
y = stat(prop),
# Why do we need this aesthetic?????
group = 1)
)
```
3. **Getting more out of statistical transformations**: the best example is getting a *3-number-summary* of your data with the `stat_summary()` *stat*.
```{r}
diamonds %>%
ggplot(mapping = aes(x = cut, y = depth)) +
stat_summary(
fun.min = min,
fun.max = max,
fun = median
)
```
## 7.2 Exercises
1. What is the default geom associated with `stat_summary()`? How could you rewrite the previous plot to use that geom function instead of the stat function?
The *geom* used appears to be `pointrange`. The following code produces the same plot as before:
```{r}
diamonds %>%
ggplot(mapping = aes(x = cut, y = depth)) +
geom_pointrange(
stat = "summary",
fun = median,
fun.min = min,
fun.max = max
)
```
The default stat for `geom_pointrange()` is `identity()` but we can add the argument `stat = "summary"` to use `stat_summary()` instead of `stat_identity()`.
2. What does `geom_col()` do? How is it different to `geom_bar()`?
`geom_col()` will represent values of the data in the *y-axis*, so it's similar to using `geom_bar(stat = "identity")`. On the other hand, `geom_bar()` makes the height of the bars proportional to the number of cases of each categorical variable (i.e. it *counts* them).
Another difference is that `geom_col()`'s default *stat* is `stat_identity()`, which leaves the data as is; while `geom_bar()`'s default *stat* is `stat_count()`, which counts the data.
3. Most geoms and stats come in pairs that are almost always used in concert. Read through the documentation and make a list of all the pairs. What do they have in common?
4. What variables does `stat_smooth()` compute? What parameters control its behavior?
`stat_smooth()` computes four variables:
1. `y`: predicted value.
2. `ymin`: lower pointwise confidence interval around the mean
3. `ymax`: upper pointwise confidence interval around the mean
4. `se`: standard error
The parameters that control `stat_smooth()` are:
1. `n`: Number of points at which to evaluate smoother.
2. `method`: Smoothing method (function) to use.
3. `formula`: Formula to use in smoothing function.
4. `se`: Display confidence interval around smooth? `TRUE` is default.
5. `span`: Controls the amount of smoothing for the default *loess* smoother. Larger numbers produce smoother lines.
6. `fullrange`: Should the fit span the full range of the plot, or just the data?
7. `level`: Level of confidence interval to use (0.95 by default).
and others (but less important, such as `na.rm`).
5. In our proportion bar chart, we need to set `group = 1`. Why? In other words what is the problem with these two graphs?
If `group = 1` is not included, then all the bars in the plot will have the same height, a height of 1. The function `geom_bar()` assumes that the groups are equal to the `x` values... and since the stat computes the counts within each group... the proportion of each group is 100% (or 1).
`group="whatever"` is a "dummy" grouping to override the default behavior, which (here) is to group by `cut` and in general is to group by the x variable. The default for `geom_bar` is to group by the x variable in order to separately count the number of rows in each level of the x variable. For example, here, the default would be for `geom_bar` to return the number of rows with `cut` equal to "Fair", "Good", etc.
However, if we want proportions, then we need to consider all levels of `cut` together. In the second plot, the data are first grouped by `cut`, so each level of `cut` is considered separately. The proportion of Fair in Fair is 100%, as is the proportion of Good in Good, etc. `group=1` (or `group="x"`, etc.) prevents this, so that the proportions of each level of cut will be relative to all levels of cut.
The problem with these two plots is that the proportions are calculated within the groups.
```{r}
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, y = after_stat(prop)))
```
```{r}
ggplot(data = diamonds) +
geom_bar(mapping = aes(x = cut, fill = color, y = after_stat(prop)))
```
## 8.Position Adjustments
You can color a bar chart using either the `colour` aesthetic, or, more usefully, `fill`:
```{r}
diamonds %>%
ggplot() +
geom_bar(aes(x = cut, color = cut))
diamonds %>%
ggplot() +
geom_bar(aes(x = cut, fill = cut))
```
Note that, in both cases, the variable mapped to `x` is the same mapped to `fill` or `color`. If you map these last aesthetics to a different variable, you get stacked bars:
```{r}
diamonds %>%
ggplot() +
geom_bar(mapping = aes(x = cut, fill = clarity))
```
## 9.Coordinate Systems
x
## 10.The layered grammar of graphics
x