-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_data_visualization.qmd
More file actions
993 lines (760 loc) · 27.3 KB
/
01_data_visualization.qmd
File metadata and controls
993 lines (760 loc) · 27.3 KB
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
---
title: "Data visualization"
author: "Max Hachemeister"
date: last-modified
date-format: iso
format: gfm
toc: true
toc-depth: 3
---
# Prerequisites
```{r}
#| label: setup
#| include: true
#| output: false
library(tidyverse)
library(palmerpenguins)
library(ggthemes)
```
## 1.2 First steps
Variable
: a quantity, quality, or property that you can measure
Value
: the state of a variable when measured. May change from measurement to measurement
Observation
: set of measurements under similar conditions. Will contain several values, each for a different variable. Sometimes also referred to as "data point"
Tabular data
: set of values, associated with a variable and an observation. It is tidy if: Each value is in its own cell. Each variable has its own column. Each observation has its own row
> [Why now attributes, when we just now learned of variables]
Check out the `penguins` tibble:
```{r}
# Variation 1
penguins
# Variation 2
glimpse(penguins)
# Variation 3
View(penguins)
# and also run the help page
?penguins
```
## 1.2.3 Creating a ggplot
```{r}
# make an empty canvas
ggplot(data = penguins)
# map flipper_length_mm and body_mass_g to the axis
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
)
# add a geom to display the single observations
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point()
```
### 1.2.4 Adding aesthetics and layers
> ["To achieve this, will we need to modify the aesthetic or the geom? If you guessed “in the aesthetic mapping, inside of aes()”, you’re already getting the hang of creating data visualizations with ggplot2! And if not, don’t worry."]
> This question is somewhat misleading compared to the answer. I 'only' guessed aesthetic, and felt demotivated after reading the more specific answer.
Same plot, but this time with points colored by species:
```{r}
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species)
) +
geom_point()
```
And also add a smooth curve:
```{r}
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g, color = species)
) +
geom_point() +
geom_smooth(method = "lm")
```
Now to have one overall line I need to write a bit different code:
```{r}
ggplot(
data = penguins,
mapping = aes(flipper_length_mm, y = body_mass_g)
) +
# move the color by species down to here
geom_point(mapping = aes(color = species)) +
geom_smooth(method = "lm")
```
Also add shapes by species for the points, so the plot is sensible for color blindness:
```{r}
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point(mapping = aes(color = species, shape = species)) +
geom_smooth(method = "lm")
```
Finishing touches on the plot:
```{r}
ggplot(data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point(mapping = aes(color = species, shape = species)) +
geom_smooth(method = "lm") +
labs(
title = "Body mass and flipper length",
subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins",
x = "Flipper length (mm)", y = "Body mass (g)",
color = "Species", shape = "Species"
) +
scale_color_colorblind()
```
> [skipped the "mapping" for geom_point in this chunk]
### 1.2.5 Exercises
#### 1. How many rows are in `penguins` ? How many columns?
```{r}
glimpse(penguins)
```
There are 344 rows and 8 columns in `penguins`.
#### 2. What does the `bill_depth_mm` variable in the `penguins` data frame describe?
```{r}
?penguins
```
`bill_depth_mm` describes the bill depth in millimeters of penguins
#### 3. Make a scatterplot of `bill_depth_mm` vs. `bill_length_mm`. That is, make a scatterplot with `bill_depth_mm` on the y-axis and `bill_length_mm` on the x-axis. Describe the relationship between the two variables.
```{r}
ggplot(data = penguins,
mapping = aes(x = bill_length_mm, y = bill_depth_mm)
) +
geom_point()
```
The scatterplot shows a rather random pattern, with a gap between bill depth 15 to 16 mm. This indicates separate groups in the data. Let's also color the points by species and get an overall regression line to further investigate that assumption:
```{r}
ggplot(
data = penguins,
mapping = aes(x = bill_length_mm, y = bill_depth_mm)
) +
geom_point(mapping = aes(color = species)) +
geom_smooth(method = "lm") +
# label the plot
labs(
title = "Bill depth and bill length",
subtitle = "Dimensions for Adelie, Chinstrap, and Gentoo Penguins",
x = "Bill length (mm)",
y = "Bill depth (mm)",
color = "Species"
) +
scale_color_colorblind()
```
Now the scatterplot exhibits the different groups and their respective relationship of bill depth and bill length. However the regression line indicates a negative trend overall, but also doesn't fit the points well. Let's make a smooth line per group:
```{r}
ggplot(
data = penguins,
mapping = aes(x = bill_length_mm, y = bill_depth_mm,
color = species)
) +
geom_point() +
geom_smooth(method = "lm") +
labs(
title = "Bill depth and bill length",
subtitle = "Dimensions and regression lines for Adelie, Chinstrap and Gentoo Penguins",
color = "Species",
x = "Bill length (mm)",
y = "Bill depth (mm)"
) +
scale_color_colorblind()
```
The regression lines now indicate a positive relationship between bill depth and bill length within each species. Interestingly the Chinstrap Penguins seem to be separated into two groups.
#### 4. What happens if you make a scatterplot of `species` vs. `bill_depth_mm`? What might be a better choice of geom?
```{r}
ggplot(
data = penguins,
mapping = aes(x = species, y = bill_depth_mm)
) +
geom_point()
```
As `species` is a categorical variable, all the points are on a line for each species. So we can somewhat see that Gentoo Penguins have generally the shortest bills, there is not much more information in this plot. Which other geom would be sensible though?
So far we the only other geom we learned is `geom_smooth`. Let's try that:
```{r}
ggplot(
data = penguins,
mapping = aes(x = species, y = bill_depth_mm)
) +
geom_smooth(method = "lm")
```
Okay that's even less informative.
So let's see what other geoms come up when I type `geom_` into the console:
```{r}
ggplot(
data = penguins,
mapping = aes(x = species, y = bill_depth_mm)
) +
geom_bin_2d()
```
Okay `geom_bin2d()` seems more informative as you can see how many observations there are for each value of `bill_depth_mm`.
I mean what we also could do, is plotting `bill_depth_mm` vs. `body_mass` and color by species, aswell as adding a regression line, like in the first example plot. Let's try that:
```{r}
ggplot(
data = penguins,
mapping = aes(x = bill_depth_mm, y = body_mass_g)
) +
geom_point(mapping = aes(color = species, shape = species)) +
geom_smooth() +
scale_color_colorblind() +
labs(
title = "Bill depth and body mass",
subtitle = "Dimensions for Adelie, Chinstrap and Gentoo Penguins",
x = "Bill depth (mm)",
y = "Body mass (mm)"
)
```
Well now we see that Gentoo Penguins, while being the heaviest, seem to have generally thinner bills. The regression line is wonky as there seem to be two groups and those are not linearly related. But yeah. That should suffice for now.
#### 5. Why does the following give an error and how would you fix it?
```{r}
#| error: true
ggplot(data = penguins) +
geom_point()
```
`geom_point` expects the `x` and `y` aesthetics to be mapped. So I would map for example `bill_depth_mm` and `body_mass_g` to `x` and `y` respectively.
#### 6. What does the `na.rm` argument do in `geom_point()`? What is the default value of the argument? Create a scatterplot where you successfully use this argument set to `TRUE`.
First check the documentation for geom_point()
```{r}
?geom_point()
```
The documentation states that this argument's default value is `FALSE`. And further down it explains that this argument removes missing values either giving out a warning or not. Let's do a plot and set `na.rm` to `TRUE`:
```{r}
ggplot(
data = penguins,
mapping = aes(x = bill_depth_mm, y = body_mass_g, color = species)
) +
geom_point(na.rm = TRUE)
```
Ah yeah, there is no more warning in the output.
#### 7. Add the following caption to the plot you made in the previous exercise:"Data come from the palmerpenguins package." Hint: Take a look at the documentation for `labs()`.
Check the documentation for labs
```{r}
?labs()
```
According to the documentation there is an `caption` argument, so I will try this for the plot:
Let's make it with shapes and for colorblind aswell
```{r}
ggplot(
data = penguins,
mapping = aes(x = bill_depth_mm, y = body_mass_g,
color = species, shape = species)
) +
# and keep the na.rm for tidy code
geom_point(na.rm = TRUE) +
scale_color_colorblind() +
labs(
title = "Bill depth and Body mass",
subtitle = "Dimensions for Adelie, Chinstrap and Gentoo Penguins",
# here comes the caption
caption = "Data comes from the palmerpenguins package.",
x = "Bill depth (mm)",
y = "Body mass (g)"
)
```
#### 8. Recreate the following visualization. What aesthetic should `bill_depth_mm` be mapped to? And should it be mapped at the global level or at the geom level?

We see a scatterplot of `body_mass_g` and `flipper_length_mm` with an added `geom_smooth()`. Everything else is default.
Let's recreate it:
```{r}
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point() +
geom_smooth(method = "lm")
```
Ah now I see that there is also `bill_depth_mm` mapped to the `color` aesthetic.
Let's add that aswell:
```{r}
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g,
color = bill_depth_mm)
) +
geom_point() +
geom_smooth(method = "lm")
```
Okay, that seems right. There are many warnings, but the plot got rendered.
#### 9. 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}
#| eval: false
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g, color = island)
) +
geom_point() +
geom_smooth(se = FALSE)
```
`geom_point()` and `geom_smooth()` tell me that this will be a scatterplot of `flipper_length_mm` and `body_mass_g` with a regression line. Ah and `color = island` tells me that the points will be colored by `island`, and I think that also makes a regression line for each `island` group.
Let's see:
```{r}
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g, color = island)
) +
geom_point() +
geom_smooth(se = FALSE)
```
Ah and the `se = false` argument for `geom_smooth()` hides the gray areas around the regression lines.
#### 10. Will these two graphs look different? Why/why not?
```{r}
#| eval: false
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point() +
geom_smooth()
ggplot() +
geom_point(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_smooth(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
)
```
Actually, I think both codes will get the same graph. The layers `geom_point()` and `geom_smooth()` are the same in each and from `?geom_point` I could read that geoms also takes the `data` and `mapping` arguments directly. So while the second code is more to type both are the same i guess.
Let's see:
```{r}
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point() +
geom_smooth()
ggplot() +
geom_point(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_smooth(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
)
```
## 1.4 Visualizing distributions
### 1.4.1 Categorical Variables
*Categorical* Variables
: aka *qualitative* variables
: can take only a small set of values
: mathematical calculations don't yield practical results
>[Why not also *qualitative* variable here, like with numerical variables?]
For example `species`.
`geom_bar()` is good for that. It counts the number of observations for each 'level' of a category and sizes the bars accordingly.
```{r}
ggplot(
data = penguins,
mapping = aes(x = species)
) +
geom_bar()
```
Use `fct_infreq()` to get the bars ordered by count.
```{r}
ggplot(
data = penguins,
mapping = aes(x = fct_infreq(species))
) +
geom_bar()
```
### 1.4.2 Numerical variables
*numerical variables*
: aka *quantitative* variables
: can take a wide range of numerical values
: you get sensible results when calculating with the values
Example `body_mass_g`.
`geom_histogram()` and `geom_density()` are good for that.
While the histogram is more true to the original distribution of the data, the density curve usually is more easy to get an intuition of the distribution. However the line in the plot is only a mathematical approximation, so some information is not visible.
Let's check it out:
```{r}
ggplot(
data = penguins,
mapping = aes(x = body_mass_g)
) +
geom_density()
```
### 1.4.3 Exercises
#### 1. Make a barplot of `species` of `penguins`, where you assing `species` to the `y` aesthetic. How is this plot different?
>> why is scatterplot written as one and bar plot written as two words?
```{r}
ggplot(
data = penguins,
mapping = aes(y = species)
) +
geom_bar()
```
Okay and the same plot with `species` on the `x` axis:
```{r}
ggplot(
data = penguins,
mapping = aes(x = species)
) +
geom_bar()
```
Gotcha, so the bars either go in `x` direction, that is vertical; or they go in `y` direction, that is, horizontal.
#### 2. How are the following two plots different? Which aesthetic, `color` or `fill`, is more useful for changing the color of the bars?
```{r}
ggplot(
data = penguins,
mapping = aes(x = species)
) +
geom_bar(color = "red")
ggplot(
data = penguins,
mapping = aes(x = species)
) +
geom_bar(fill = "red")
```
So `color` applies to the outline and `fill` to the area of the geom.
#### 3. What does the `bins` argument in `geom_histogram()` do?
I can remember this.
The `bins`... hold up!
So `bins` and `binwidth` are separate arguments.
`binwidth` was explained before. Its value defines how wide each bin is, in the units of the variable that is mapped to the geom.
I think with `bins` you define how many bins in total you want the data to be sorted into.
Let's try it by making a histogram with ten bins:
```{r}
ggplot(
data = penguins,
mapping = aes(x = body_mass_g)
) +
geom_histogram(bins = 10)
```
Yep, that's ten.
#### 4. Make a histogram of the `carat` variable in the `diamonds` dataset that is available when you load the tidyverse package. Experiment with different binwidths. What binwidth reveals the most interesting patterns?
Let's first take a look at the dataset, to get a sense for the scale of the `carat` and also check the documentation:
```{r}
glimpse(diamonds)
?diamonds
```
Good, it says `carat` has values from 0.2 to 5.01.
So I start with a `binwidth` of 0.1 and 0.01, to see what histograms I get.
```{r}
ggplot(
data = diamonds,
mapping = aes(x = carat)
) +
geom_histogram(binwidth = 0.1)
ggplot(
data = diamonds,
mapping = aes(x = carat)
) +
geom_histogram(binwidth = 0.01)
```
Interesting!
There seems to be a pattern. A lot of diamonds are around values that are a quarter of a carat.
Let's do two things.
One histogram with `binwidth` 0.25 to check if I read the pattern rigth and one with 0.005 to see whether it repeats on even lower scale.
```{r}
ggplot(
data = diamonds,
mapping = aes(x = carat)
) +
geom_histogram(binwidth = 0.25)
ggplot(
data = diamonds,
mapping = aes(x = carat)
) +
geom_histogram(binwidth = 0.005)
```
Ahh!
The 0.25 did not bring something new. I misinterpreted that.
But check out the 0.005 histogram! There are some empty bins. I guess we found the minimal carat they could measure, which is 0.01.
And it seems that there are more diamonds on whole carat and quarter fractions.
Is probably a size that buyers like to see.
## 1.5 Visualizing relationships
### 1.5.1 A numerical and a categorical variable
Example, boxplot of body mass and species:
```{r}
ggplot(
data = penguins,
mapping = aes(x = species, y = body_mass_g)
) +
geom_boxplot()
```
Or alternatively density plots by species:
```{r}
ggplot(
data = penguins,
mapping = aes(x = body_mass_g, color = species)
) +
geom_density(linewidth = 0.75)
```
To make it more appealing, add `fill`, but make the overlap visible with the `alpha` argument:
```{r}
ggplot(
data = penguins,
mapping = aes(x = body_mass_g, color = species, fill = species)
) +
geom_density(alpha = 0.5, linewidth = 0.75)
```
mapping to an aesthetic
: have the visual attribute vary based on the values of the variable
setting an aesthetic
: set the value 'manually'
### 1.5.2 Two categorical variables
Example, stacked bar plots of `island` and `species`.
First one so you can see the raw counts:
```{r}
ggplot(
data = penguins,
mapping = aes(x = island, fill = species)
) +
geom_bar()
```
Second one to see the proportions, with `position = "fill"` argument:
```{r}
ggplot(
data = penguins,
mapping = aes(x = island, fill = species)
) +
geom_bar(position = "fill")
```
### 1.5.3 Two numerical variables
Example, scatterplot of flipper length and body mass.
Just like in section 1.1 and 1.2
```{r}
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g)
) +
geom_point()
```
### 1.5.4 Three or more variables
Example, scatterplot of flipper length and body mass, with colors by species and shape by island.
```{r}
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g,
color = species, shape = island)
) +
geom_point()
```
But yeah, that's pretty busy and relatively less informative.
At this point, splitting the plot into facets with `facet_wrap()` would be one solution.
Note the `~` in the facet wrap function. This is the *tilde* sign, which is used in R for *formulas*. More on that later though.
```{r}
ggplot(
data = penguins,
mapping = aes(x = flipper_length_mm, y = body_mass_g,
color = species, shape = species)
) +
geom_point() +
facet_wrap(~island)
```
### 1.5.5 Exercises
#### 1. The `mpg` data frame that is bundled with the ggplot2 package contains 234 observations collected by the US Environmental Protection Agency on 38 car models.
- Which variables in `mpg` are categorical?
- Which variables are numerical?
Hint: Type `?mpg` to read the documentation for the dataset.
- How can you see this information when you run `mpg`?
Read the documentation, `glimpse()` the dataframe and run `mpg` directly:
```{r}
?mpg
glimpse(mpg)
mpg
```
The documentation explains the columns further, but does not list the variable type, while `glimpse()` gives a short overview of the dataframe and shows the variable type in its second row. You can find this information also when calling `mpg` directly, then it's right under each column header. You have to scroll through the columns though.
In total there are six categorical variables (basically all `<chr>` columns) and five numerical variables.
The categorical variables are `manufacturer`, `model`, `trans`, `drv`, `fl` and `class`.
The numerical variables are `displ`, `year`, `cyl`, `cty` and `hwy`.
Well come to think of it, `cyl`, which is the number of cylinders might count as a categorical variable, as there are usually a few possible values for that and arithmetic doesn't seem sensible in that case.
#### 2. Make a scatterplot of `hwy`vs. `displ` using the `mpg` data frame.
> Next, map a third numerical variable to `color`, then `size`, then both `color` and `size`, then `shape`. How do these aesthetics behave differently for categorical vs. numerical variables?
Scatterplot of `hwy` vs. `displ`.
The vs. implicates for me that you read it like 'y vs. x'. Well that's at least a convention I follow.
```{r}
ggplot(
data = mpg,
mapping = aes(x = displ, y = hwy)
) +
geom_point()
```
Adding `trans`, a categorical to `color`:
```{r}
ggplot(
data = mpg,
mapping = aes(x = displ, y = hwy, color = trans)
) +
geom_point()
```
Looks very busy to me. But I can make out that auto(l4) and manual(m5) seem to be the most common transmission types.
Add `cty` as a numerical variable to `size`.
```{r}
ggplot(
data = mpg,
mapping = aes(x = displ, y = hwy,
color = trans, size = cty)
) +
geom_point()
```
So it seems like it put the numerical variable into bins and then draws the point size accordingly.
Now map `cty` to both `color` and `size`:
```{r}
ggplot(
data = mpg,
mapping = aes(x = displ, y = hwy,
color = cty, size = cty)
) +
geom_point()
```
Now we see that `color` and `size` of the points are continuous and the bins are just in the legend to help you orient.
Now map `cty` only to shape:
```{r}
#| error: true
ggplot(
data = mpg,
mapping = aes(x = displ, y = hwy,
shape = cty)
) +
geom_point()
```
Ah okay, continuous variables are not by default mapable to `shape`.
#### 3. In the scatterplot of `hwy` vs. `dspl`, what happens if you map a third variable to `linewidth`?
I will map `cty` to `linewidth`.
Interesting what will happen, as it's just points. So what does `linewidth` even apply to?
Let's see:
```{r}
#| warning: true
ggplot(
data = mpg,
mapping = aes(x = displ, y = hwy)
) +
geom_point(
mapping = aes(linewidth = cty)
)
```
Ah, so `linewidth` is unknown for the scatterplot and therefore ignored, but at least a warning is given.
#### 4. What happens if you map the same variable to multiple aesthetics?
Let's map `hwy` to `x`, `y` and `color`:
```{r}
ggplot(
data = mpg,
mapping = aes(x = hwy, y = hwy, color = hwy)
) +
geom_point()
```
Seems like it did what I asked for. It's just not much new information. We can see the distribution a bit.
#### 5. Make a scatterplot of `bill_depth_mm` vs. `bill_length_mm` and color the points by `species`.
> What does adding coloring by species reveal about the relationship between these two variables? What about faceting by `species`?
> [!note] Why is the second `species` not formated like the other occurences?
So there are two visualizations to be done. Let's start with the scatterplot:
```{r}
ggplot(
data = penguins,
mapping = aes(x = bill_length_mm, y = bill_depth_mm, color = species)
) +
geom_point()
```
The colors in the plot make out the distinction between the species. You can see that the points for each form separate groups in the value ranges of bill length and bill depth.
Let's do the facets now!
I will keep the coloring, as I think it won't harm the appeal of the plot.
```{r}
ggplot(
data = penguins,
mapping = aes(x = bill_length_mm, y = bill_depth_mm, color = species)
) +
geom_point() +
facet_wrap(~ species)
```
Well you can see the same. The species make up clusters. So Gentoo penguins have the longest but thinnest bills, while Adelie and Chinstrap penguins have similarly wide bills, even though Adelies have generally the shortest bills of all three species.
I think though that you can see the relation of those groups better when they are all in one plot, whereas the faceting makes the individual ranges more clear.
#### 6.
> Why does the following yield two separate legends? How would you fix it to combine the two legends?
Sample code:
```{r}
ggplot(
data = penguins,
mapping = aes(
x = bill_length_mm, y = bill_depth_mm,
color = species, shape = species
)
) +
geom_point() +
labs(color = "Species")
```
The `labs` makes it so that `shape` and `color` get a different label for their legends. Maybe if I leave `labs` out, both will become one legend.
Let's see:
```{r}
ggplot(
data = penguins,
mapping = aes(
x = bill_length_mm, y = bill_depth_mm,
color = species, shape = species
)
) +
geom_point()
```
Good, that solved it.
And if I wanted to have "Species" with the capital "S" I would have to set this for both aesthetics in the `labs` function.
```{r}
ggplot(
data = penguins,
mapping = aes(
x = bill_length_mm, y = bill_depth_mm,
color = species, shape = species
)
) +
geom_point() +
labs(
color = "Species",
shape = "Species"
)
```
#### 7.
> Create the two following stacked bar plots. Which question can you answer with the first one? Which question can you answer with the second one?
```{r}
ggplot(penguins, aes(x = island, fill = species)) +
geom_bar(position = "fill")
ggplot(penguins, aes(x = species, fill = island)) +
geom_bar(position = "fill")
```
The first stacked bar plot answers the question: "What is the proportion of species among all the penguins of each island?"
The second stacked bar plot answers the question: "How are the penguins of each species distributed among the islands?"
You can roughly read it like: "What is the proportion of `fill` among all the 'observational units' for each `x`?"
So in case of the second plot it would read: "What is the proportion of `islands` among all the 'penguins' for each `species`?
Yeah, you'd have to tweak it a bit case by case.
## 1.6 Saving your plots
### 1.6.1 Exercises
#### 1.
> Run the following lines of code. Which of the two plots is saved as `mpg-plot.png`? Why?
Example code:
```{r}
ggplot(mpg, aes(x = class)) +
geom_bar()
ggplot(mpg, aes(x = cty, y = hwy)) +
geom_point()
ggsave("mpg-plot.png")
```
Can I display this plot somehow from the file?
Well the internet search shows some extra packages that can do that, but not natively within R-Studio. So you will have to believe me that
I've checked the `mpg-plot.png` and it shows the scatterplot.
This reflects the mentioned behavior of `ggsave()`, saving the most recently rendered plot, which in the code above is the scatterplot, if you were to run the chunk as a whole.
#### 2.
> What do you need to change in the code above to save the plot as a PDF instead of a PNG? How could you find out what types of image files would work in `ggsave()`?
To see what `ggsave()` can do, I would check the documentation like so:
```{r}
?ggsave()
```
There it says for the argument "device", that it can do a bunch of formats, e.g. "eps", "ps", *"pdf"*, "png" and such. In the end it's also described that it guesses the format based on the `filename` extension, if not stated otherwise in the "device" argument.
So to save the plot as "pdf" I can just name the output accordingly:
```{r}
ggplot(mpg, aes(x = cty, y = hwy)) +
geom_point()
ggsave("mpg-plot.pdf")
```
## 1.7 Common problems
Writing code that works on first try takes practice and consideration.
Mostly something won't work.
Be patient and read your code line by line.
Check the documentation. In the beginning especially the code examples for the functions.
Also the web search, or LLM can be of good help, if you're stuck.
## 1.8 Summary
I've made my first scatterplot, that would be ready to publish. With labels, shapes and colorblind coloring.
I learned the basics of `ggplot()`. How it makes up plots of different layers and how to control those elements, by either "setting" them directly, or "mapping" them to express values of a variable.
I learned several plots to visualize different relationships, for example, two numeric variables, one categorical and one numeric and such.
So i also learned about the distinction between those variable types.
In the end I learned to save a plot and how to troubleshoot my code a bit.