-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path03-colors.Rmd
973 lines (699 loc) · 33 KB
/
03-colors.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
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
---
title: "Lab 03: Colors with Animal Sounds"
subtitle: "CS631"
author: "Alison Hill"
output:
html_document:
theme: flatly
toc: TRUE
toc_float: TRUE
toc_depth: 2
number_sections: TRUE
code_folding: hide
---
```{r setup, include = FALSE, cache = FALSE}
knitr::opts_chunk$set(error = TRUE, comment = NA, warning = FALSE, errors = FALSE, message = FALSE, tidy = FALSE, cache = FALSE)
library(RColorBrewer)
library(wesanderson)
library(ggthemes)
library(beyonce)
library(viridis)
```
# Overview
There are 10 challenges total- none are in the "continuous colors" section, but you can use that section to complete the tenth challenge on your own. Upload your knitted html document by next Wednesday at noon to Sakai!
# Slides for today
```{r}
knitr::include_url("slides/03-slides.html")
```
# Packages
Other packages will be needed to be installed as you go- reveal the first code chunks when in doubt!
```{r}
library(tidyverse)
```
# Read in the data
Use this code chunk to read in the data available at [http://bit.ly/cs631-meow](http://bit.ly/cs631-meow):
```{r}
sounds <- read_csv("http://bit.ly/cs631-meow")
```
Or store it locally:
```{r}
sounds <- read_csv(here::here("data", "animal_sounds_summary.csv"))
```
# Colour vs fill aesthetic
Fill and colour scales in ggplot2 can use the same palettes. Some shapes such as lines only accept the colour aesthetic, while others, such as polygons, accept both colour and fill aesthetics. In the latter case, the colour refers to the border of the shape, and the fill to the interior.
```{r echo = FALSE}
## A look at all 25 symbols
df <- data.frame(x = 1:5,
y = rep(rev(seq(0, 24, by = 5)), each = 5),
z = 1:25)
s <- ggplot(df, aes(x = x, y = y)) +
scale_shape_identity() +
geom_text(aes(label = z, y = y - 1)) +
theme_void()
s + geom_point(aes(shape = z), size = 4)
```
---
All symbols have a foreground colour, so if we add `color = "navy"`, they all are affected.
```{r}
s + geom_point(aes(shape = z), size = 4, colour = "navy")
```
---
While all symbols have a foreground colour, symbols 21-25 also take a background colour (fill). So if we add `fill = "orchid"`, only the last row of symbols are affected.
```{r}
s + geom_point(aes(shape = z), size = 4, colour = "navy", fill = "orchid")
```
# Data
For the rest of today, we'll play with the `sounds` dataset. This data was derived from the R package [`wordbankr`](http://langcog.github.io/wordbankr/), an R interface to access [Wordbank](http://wordbank.stanford.edu)- an open source database of children's vocabulary development. The tool used to measure children's language and communicative development in this database is the [MacArthur-Bates Communicative Development Inventories (MB-CDI)](http://mb-cdi.stanford.edu). The MD-CDI is a parent-reported questionnaire.
Here is a glimpse of the data:
```{r}
glimpse(sounds)
```
Note that the unit of observation here is one-row-per-age-group/animal sound.
Variables you need for this lab:
- `age`: child age in months
- `sound`: a string describing a type of animal sound
- `kids_produce`: the number of parents who answered "yes, my child produces this animal sound" (note that if the child produces a sound it is assumed that they understand it as well)
- `kids_respond`: the number of parents who responded to this question at all
- `prop_produce`: the proportion of kids whose parents endorsed that their child produces this animal sound, out of all questionnaires administered (i.e., `kids_produce / kids_respond`)
Other variables in this dataset:
- `kids_understand`: the number of parents who answered "yes, my child understands what this animal sound means" (note that a child can understand the sound but not produce it)
- `prop_understand`: the proportion of kids whose parents endorsed that their child understands this animal sound, out of all questionnaires administered (i.e., `kids_understand / kids_respond`)
# Discrete vs continuous variables
[WHAT IS THE DIFFERENCE BETWEEN CATEGORICAL, ORDINAL AND INTERVAL VARIABLES?](https://stats.idre.ucla.edu/other/mult-pkg/whatstat/what-is-the-difference-between-categorical-ordinal-and-interval-variables/)
In order to use color with your data, most importantly, you need to know if you’re dealing with discrete or continuous variables.
## Discrete color palettes
Discrete color palettes work best when you want to color by a qualitative variable. Qualitative variables tend to be either categorical or ordinal. Different variables can be qualitative or quantitative depending on context.
In this dataset, `sound` is a categorical variable with 3 possible values:
```{r}
sounds %>%
distinct(sound) %>%
knitr::kable()
```
We could map arbitrary numbers onto each of these sounds, like 1, 2, and 3- but the numbers still would not mean anything. That is, there is no intrinsic ordering to these categories. Examples of common pure categorical variables are race or ethnicity, gender, hair color, eye color, etc. Coloring by sound is used as a way to *distinguish* the data for different sounds from each other (read more here: http://serialmentor.com/dataviz/color-basics.html#color-as-a-tool-to-distinguish)
## Continuous color palettes
Continuous color palettes work best when you want to color by a quantitative variable. Quantitative variables tend to be either ordinal or continuous. In this dataset, `age` (in months) can only take on a limited set of values:
```{r}
sounds %>%
distinct(age) %>%
pull
```
However, in the following plots, we'll treat age as a continuous variable plotted across the x-axis. In some contexts, this kind of variable could be treated as a ordinal variable. However, for color purposes, this would not ideal here since there are 11 "categories" (see http://serialmentor.com/dataviz/color-pitfalls.html). Age has a natural and meaningful order: a child who is 9 months old is 1 month older than one who is 8 months old. So, we'll use that natural ordering to our advantage and not use color to represent age as a variable. When you *do* apply a continuous color palette, you'll want to use color to your advantage to [represent data values](http://serialmentor.com/dataviz/color-basics.html#color-to-represent-data-values).
# Know your data
<div class="panel panel-success">
<div class="panel-heading">Challenge #1:</div>
<div class="panel-body">
- How many variables?
- Which variables are continuous?
- Which ones are categorical or ordinal?
- How many total kids do we have data for?
- How many ages (in months)?
- How many kids per age?
- How many types of animal sounds? What are they?
</div>
</div>
Let's start just by getting a feel for how many kids produce each kind of sound, across the full age range. We could make a table:
```{r}
sounds %>%
group_by(sound) %>%
summarize(total_produce = sum(kids_produce)) %>%
knitr::kable()
```
Or we could make a simple bar plot:
```{r}
ggplot(sounds, aes(x = sound, y = kids_produce)) +
geom_col() +
labs(x = "Sound", y = "Total Children Producing")
```
For this kind of plot, we don't really need color. What if we want to see how the number of kids who produce each sound varies by age? We'll change the x-axis to age and instead `facet_wrap` by `sound`, and make the y-axis a proportion instead of counts.
```{r}
ggplot(sounds, aes(x = age, y = prop_produce)) +
geom_col() +
labs(x = "Age (mos)", y = "Proportion of Children Producing") +
facet_wrap(~sound)
```
The bar geom makes this a little hard to read and compare across facets though. Let's try points instead.
```{r}
ggplot(sounds, aes(x = age, y = prop_produce)) +
geom_point() +
labs(x = "Age (mos)", y = "Proportion of Children Producing") +
facet_wrap(~sound)
```
That is a little better! Facets allow us to parse the relationship between two quantitative variables (here, age and proportion of kids producing) by a qualitative variable (here, type of sound). Another way we could do this, instead of facetting, is to use color. This would make it easier to compare proportions at each age.
# Discrete colors
Let's start with a base plot with age (in months) along the x-axis and the proportion of children producing each word along the y-axis, using points as the geometric object. Set the size of the points to 2 and change the x- and y-axis labels to "Age (months)" and "Proportion of Children Producing", respectively.
```{r}
ggplot(sounds, aes(x = age, y = prop_produce)) +
geom_point(size = 2) +
labs(x = "Age (months)", y = "Proportion of Children Producing")
```
## Default discrete palette
<div class="panel panel-success">
<div class="panel-heading">Challenge #2:</div>
<div class="panel-body">
Take the plot we just made, and edit the code to map the color of the points to the type of sound produced *at the geom level*. The colors that show up are the default discrete palette in `ggplot2`.
```{r}
ggplot(sounds, aes(x = age, y = prop_produce)) +
geom_point(aes(color = sound), size = 2) +
labs(x = "Age (months)", y = "Proportion of Children Producing")
```
</div>
</div>
<div class="panel panel-success">
<div class="panel-heading">Challenge #3:</div>
<div class="panel-body">
Try adding `geom_line()` to this plot to connect the dots. Does this look right? Use `?geom_line` to figure out how this geom connects the dots by default, and which aesthetic can be used to connect cases together. Try editing your code to draw 3 black lines- one for each sound.
```{r}
# Does this look right? no!
ggplot(sounds, aes(x = age, y = prop_produce)) +
geom_line() +
geom_point(aes(color = sound), size = 2) +
labs(x = "Age (months)", y = "Proportion of Children Producing")
```
```{r}
# A possible solution
ggplot(sounds, aes(x = age, y = prop_produce)) +
geom_line(aes(group = sound)) +
geom_point(aes(color = sound), size = 2) +
labs(x = "Age (months)", y = "Proportion of Children Producing")
```
</div>
</div>
<div class="panel panel-success">
<div class="panel-heading">Challenge #4:</div>
<div class="panel-body">
Make two plots:
1. Recreate the plot above, but this time map color to the type of sound produced for both the point and line geoms. Pay attention to the order of the layers you are adding- you may wish to place `geom_line` *before* `geom_point` so the lines are always "painted" underneath the points.
2. Instead of `geom_line`, add a loess line using `geom_smooth`. Use `?geom_smooth` to figure out how to get rid of the grey standard error ribbon. You may also want to increase the line width.
```{r}
# Does this look right? yes!
ggplot(sounds, aes(x = age, y = prop_produce, color = sound)) +
geom_line() +
geom_point(size = 2) +
labs(x = "Age (months)", y = "Proportion of Children Producing")
ggplot(sounds, aes(x = age,
y = prop_produce,
color = sound)) +
geom_smooth(se = FALSE, lwd = .5) +
geom_point(size = 2) +
labs(x = "Age (months)", y = "Proportion of Children Producing")
```
</div>
</div>
Why does this work? To tell `geom_line` how to connect your dots, you can either:
- Map the `group` aesthetic (so `aes(group = sound)`), or
- Map the `color` aesthetic globally (`aes(color = sound)`.
Because `geom_line` understands the `color` aesthetic, it will try to draw separate lines for each color. Here that translates to three lines, one for each sound, which is what we want!
## Brief aside: factors
At this point, our plot is looking pretty good. But you may have noticed that the legend order doesn't match the lines. We can fix that using the [`forcats` package](http://forcats.tidyverse.org), which is `for` `cat`egorical variables. There are lots of functions in `forcats`, and you can install & load it separately, although `forcats` is loaded with the `tidyverse`.
```{r eval = FALSE}
install.packages("forcats")
library(forcats)
```
We'll use the `fct_reorder2` function, which works for when you have a line chart of two quantitative variables, colored by a factor variable. Let's see the difference.
```{r}
sounds <- sounds %>%
mutate(sound = as.factor(sound))
sound_traj <- ggplot(sounds, aes(x = age,
y = prop_produce,
color = fct_reorder2(sound, age, prop_produce))) +
geom_smooth(se = FALSE, lwd = .5) +
geom_point(size = 2) +
labs(x = "Age (months)",
y = "Proportion of Children Producing",
color = "sound")
sound_traj
```
MUCH BETTER! Save your plot object as `sound_traj`. Now we can start playing with the actual colors.
## Set luminance and saturation (chromaticity)
The default qualitative palette works fine here. The addition of [`scale_color_hue`](http://ggplot2.tidyverse.org/reference/scale_hue.html) changes nothing.
```{r}
sound_traj +
scale_color_hue()
```
We can also change these settings within the default color palette, where the arguments are:
- `h` = range of hues to use, in [0, 360]
- `l` = luminance (lightness)
- `c` = chroma (intensity of color)
```{r}
# Change hue (l and c are defaults)
sound_traj +
scale_color_hue(h = c(0, 90), l = 65, c = 100)
# Use luminance=45, instead of default 65
sound_traj +
scale_color_hue(l = 45)
# Reduce saturation (chroma) from 100 to 50, and increase luminance
sound_traj +
scale_color_hue(l = 75, c = 50)
```
## Set discrete colors
We can change the actual colors used by adding the layer `scale_color_manual` or `scale_fill_manual`. Confusion between which to use when is often the cause of much frustration!
To name more than one color, which you often want to do, use `c()`. In the parentheses, named colors and hex colors are always in quotes.
```{r}
sound_traj +
scale_color_manual(values = c("cornflowerblue",
"seagreen", "coral"))
```
<div class="panel panel-success">
<div class="panel-heading">Challenge #5:</div>
<div class="panel-body">
View the code blocks below. Copy and paste the code to run them in your own file. Why do neither of the following code blocks change the colors of the points and lines? Use your words :) *(the answer is below the challenge, but try to trouble-shoot on your own first)*
```{r}
ggplot(sounds, aes(x = age,
y = prop_produce,
color = fct_reorder2(sound, age, prop_produce))) +
geom_smooth(se = FALSE, lwd = .5) +
geom_point(size = 2) +
labs(x = "Age (months)",
y = "Proportion of Children Producing",
color = "sound") +
scale_fill_manual(values = c("cornflowerblue",
"seagreen", "coral"))
```
```{r}
ggplot(sounds, aes(x = age,
y = prop_produce,
fill = fct_reorder2(sound, age, prop_produce))) +
geom_smooth(se = FALSE, lwd = .5) +
geom_point(size = 2) +
labs(x = "Age (months)",
y = "Proportion of Children Producing",
fill = "sound") +
scale_fill_manual(values = c("cornflowerblue",
"seagreen", "coral"))
```
</div>
</div>
Answers:
- In the first, we used `scale_fill_manual`, but the in the global aesthetics, we mapped the `color`, not `fill`, aesthetic onto the `sound` variable.
- In the second, we did define the `fill` aesthetic and used `scale_fill_manual`, so that is good. But `geom_line` only understands the `color` aesthetic, not `fill`. And for `geom_point`, the default shape for is 19, which does not understand the `fill` aesthetic.
<div class="panel panel-success">
<div class="panel-heading">Challenge #6:</div>
<div class="panel-body">
Start with this plot:
```{r}
sound_traj
```
Add a black outline to the points, and color the inside of the points and the lines by `sound` using the default discrete color palette. You may also wish to edit the legends on this plot: `geom_smooth` has an argument called `show.legend = FALSE`. See if you prefer the plot with this change.
If this was easy, try applying the same custom color palette to the inside of the points and to the lines.
```{r}
ggplot(sounds, aes(x = age,
y = prop_produce,
fill = fct_reorder2(sound, age, prop_produce))) +
geom_smooth(aes(color = fct_reorder2(sound, age, prop_produce)),
se = FALSE, lwd = .5, show.legend = FALSE) +
geom_point(size = 2, shape = 21) +
labs(x = "Age (months)",
y = "Proportion of Children Producing",
fill = "sound")
```
```{r}
ggplot(sounds, aes(x = age,
y = prop_produce,
fill = fct_reorder2(sound, age, prop_produce))) +
geom_smooth(aes(color = fct_reorder2(sound, age, prop_produce)),
se = FALSE, lwd = .5, show.legend = FALSE) +
geom_point(size = 2, shape = 21) +
labs(x = "Age (months)",
y = "Proportion of Children Producing",
fill = "sound") +
scale_fill_manual(values = c("cornflowerblue",
"seagreen", "coral")) +
scale_color_manual(values = c("cornflowerblue",
"seagreen", "coral"))
```
</div>
</div>
You can also define your color palette as a vector outside of `ggplot2`. Below, I made an object called `my_colors` outside of `ggplot2`. To use it, we call that object within the `scale_colour_manual` function.
```{r}
my_colors <- c("cadetblue", "steelblue", "salmon") # quote color names
sound_traj +
scale_color_manual(values = my_colors) # note: not in quotes
```
<div class="panel panel-success">
<div class="panel-heading">Challenge #7:</div>
<div class="panel-body">
Define a custom color palette using hexadecimal colors (#rrggbb), and apply it using `scale_color_manual` to your `sound_traj` plot. Some basic ones are here:
https://sashat.me/2017/01/11/list-of-20-simple-distinct-colors/
Parse the hexadecimal string like so: #rrggbb, where rr, gg, and bb refer to color intensity in the red, green, and blue channels, respectively.
```{r}
# from https://github.com/mwaskom/seaborn/blob/master/seaborn/palettes.py
sb_colorblind <- c("#0072B2", "#009E73", "#D55E00",
"#CC79A7", "#F0E442", "#56B4E9")
sound_traj +
scale_colour_manual(values = sb_colorblind)
```
</div>
</div>
## Built-in discrete palettes
### Colorbrewer
To use Colorbrewer palettes, you'll need to install the `RColorBrewer` package from CRAN. This chunk of code tells you how:
```{r eval = FALSE}
install.packages("RColorBrewer")
library(RColorBrewer)
```
Colorbrewer has a few qualitative palettes named: Accent, Dark2, Paired, Pastel1, Pastel2, Set1, Set2, Set3. Here is how to view them:
```{r}
brewer.pal(5, "Dark2") # list 5 hex colors
display.brewer.pal(5, "Dark2") # view 5 hex colors
```
And here is how you use them:
```{r}
sound_traj +
scale_color_brewer(palette = "Dark2")
```
### Wes Anderson palettes
My favorite! To use Wes Anderson palettes, you'll need to install the `wesanderson` package from CRAN. This chunk of code tells you how:
```{r eval = FALSE}
install.packages("wesanderson")
library(wesanderson)
```
```{r}
names(wes_palettes) # all the palette names
wes_palette("GrandBudapest2") # view named palette
wes_palette("GrandBudapest2")[1:4] # list first 4 hex colors
wes_palette("GrandBudapest2")[c(1,4)] # list colors 1 and 4
```
To use these palettes, use `scale_color_manual` where `values` is set to `wes_palette("name")`. For example:
```{r}
sound_traj +
scale_color_manual(values = wes_palette("Darjeeling"))
sound_traj +
scale_color_manual(values = wes_palette("FantasticFox"))
```
<div class="panel panel-success">
<div class="panel-heading">Challenge #8:</div>
<div class="panel-body">
What if you just don't want to use the colors in the order they are in? Use a `wes_palette` of your choice. Using our code from above, try picking the last 3 colors of a palette. Add it to your `sound_traj` plot.
If this was easy, try using colors 2, 3, and 5 instead.
```{r}
sound_traj +
scale_color_manual(values = wes_palette("Darjeeling")[3:5])
sound_traj +
scale_color_manual(values = wes_palette("FantasticFox")[c(2, 3, 5)])
```
</div>
</div>
### `ggthemes` palettes
To use these palettes, you'll need to install the `ggthemes` package from CRAN. This chunk of code tells you how:
```{r eval = FALSE}
install.packages("ggthemes")
library(ggthemes)
```
```{r}
sound_traj +
scale_color_fivethirtyeight()
sound_traj +
scale_color_economist()
```
### Palettes from the Queen Bee
To use [Beyonce palettes](https://github.com/dill/beyonce), you'll need to install the `beyonce` package from GitHub using `devtools::install_github()`. This chunk of code tells you how:
```{r eval = FALSE}
install.packages("devtools")
devtools::install_github("dill/beyonce")
library(beyonce)
```
Note that a number of students had installation problems with this package! Move on if you do.
```{r}
beyonce_palette(18)
```
```{r}
sound_traj +
scale_color_manual(values = beyonce_palette(18)[3:5])
```
Here we'll only use the first, fourth, and fifth colors in the palette.
```{r}
sound_traj +
scale_color_manual(values = beyonce_palette(18)[c(1, 4, 5)])
```
### Viridis palettes
To use, you'll need to install the `viridis` package from CRAN. This chunk of code tells you how:
```{r eval = FALSE}
install.packages("viridis")
library(viridis)
```
Read more here in the [viridis vignette](https://cran.r-project.org/web/packages/viridis/vignettes/intro-to-viridis.html). The default argument for `discrete` is FALSE, so to use the discrete palettes you need to set `discrete = TRUE`. There are four colormap options available:
- "magma" (or "A"),
- "inferno" (or "B"),
- "plasma" (or "C"),
- "viridis" (or "D", the default option).
```{r}
sound_traj +
scale_color_viridis(discrete = TRUE) +
theme_minimal()
sound_traj +
scale_color_viridis(discrete = TRUE, option = "plasma") +
theme_minimal()
```
<div class="panel panel-success">
<div class="panel-heading">Challenge #9:</div>
<div class="panel-body">
Use the `viridis` package to color the points by and the lines by `sound`; make the outline of the points "midnightblue". Pick any colormap option, and play with `theme_bw` or `theme_minimal` to see what you like.
```{r}
ggplot(sounds, aes(x = age,
y = prop_produce,
fill = fct_reorder2(sound, age, prop_produce))) +
geom_smooth(aes(color = fct_reorder2(sound, age, prop_produce)),
se = FALSE, lwd = .5, show.legend = FALSE) +
geom_point(size = 2, shape = 21, colour = "midnightblue") +
labs(x = "Age (months)",
y = "Proportion of Children Producing",
fill = "sound") +
scale_fill_viridis(discrete = TRUE) +
scale_color_viridis(discrete = TRUE) +
theme_minimal()
```
</div>
</div>
## Greyscale for discrete
Use `scale_color_grey` or `scale_fill_grey`, or sometimes both depending on your geoms and the aesthetics they understand.
```{r}
sound_traj +
scale_color_grey() +
theme_minimal()
```
Set start and end
```{r}
sound_traj +
scale_color_grey(start = 0.2, end = .8)
```
Make the same plot but make points outlined in black
```{r}
ggplot(sounds, aes(x = age,
y = prop_produce,
fill = fct_reorder2(sound, age, prop_produce))) +
geom_smooth(aes(color = fct_reorder2(sound, age, prop_produce)),
se = FALSE, lwd = .5, show.legend = FALSE) +
geom_point(size = 2, shape = 21) +
labs(x = "Age (months)",
y = "Proportion of Children Producing",
fill = "sound") +
scale_fill_grey(start = 0.3, end = 1) +
scale_color_grey(start = 0.3, end = 1)
```
Suggest redundancy in greyscale- try changing line type instead of line (or in addition to) line color.
Change line type by `sound`, set color to black.
```{r}
ggplot(sounds, aes(x = age,
y = prop_produce,
fill = fct_reorder2(sound, age, prop_produce))) +
geom_smooth(aes(lty = fct_reorder2(sound, age, prop_produce)), color = "black",
se = FALSE, lwd = .5, show.legend = FALSE) +
geom_point(size = 2, shape = 21) +
labs(x = "Age (months)",
y = "Proportion of Children Producing",
fill = "sound") +
scale_fill_grey(start = 0.3, end = 1)
```
Change both!
```{r}
ggplot(sounds, aes(x = age,
y = prop_produce,
fill = fct_reorder2(sound, age, prop_produce))) +
geom_smooth(aes(color = fct_reorder2(sound, age, prop_produce),
lty = fct_reorder2(sound, age, prop_produce)),
se = FALSE, lwd = .5, show.legend = FALSE) +
geom_point(size = 2, shape = 21) +
labs(x = "Age (months)",
y = "Proportion of Children Producing",
fill = "sound") +
scale_fill_grey(start = 0.3, end = .8) +
scale_color_grey(start = 0.3, end = .8)
```
## Colorblind-friendly palettes
The [`colorblindr` package](https://github.com/clauswilke/colorblindr) can be used to "simulate colorblindness in production-ready R figures." To use this package, you'll need to first install the `cowplot` package from GitHub using `devtools::install_github()`. You'll also need to install the `colorspace` package from CRAN. Finally, you can then use `devtools::install_github()` again to install the `colorblindr` package. This code chunk shows you how to do all 3 installs to use the `colorblindr` package:
```{r eval = FALSE}
devtools::install_github("wilkelab/cowplot")
install.packages("colorspace", repos = "http://R-Forge.R-project.org")
devtools::install_github("clauswilke/colorblindr")
```
To use:
```{r}
# save a ggplot object
my_sound_traj <- sound_traj +
scale_color_manual(values = beyonce_palette(18)[c(1, 4, 5)])
```
View that figure after color-vision-deficiency simulation:
```{r}
library(colorblindr)
cvd_grid(my_sound_traj)
```
You can also use the colorblind-friendly palette in this package using `scale_color_OkabeIto` and `scale_fill_OkabeIto`:
```{r}
cb_sound_traj <- sound_traj +
scale_color_OkabeIto()
cb_sound_traj
cvd_grid(cb_sound_traj)
```
You can still use this colorblind-friendly palette without the `colorblindr` package though. [Here](http://jfly.iam.u-tokyo.ac.jp/color/) are the colors!
![](http://jfly.iam.u-tokyo.ac.jp/color/image/pallete.jpg)
The [Cookbook for R](http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/#a-colorblind-friendly-palette) provided the matching hex colors too to make life easier:
```{r}
cbbPalette <- c("#000000", "#E69F00", "#56B4E9", "#009E73", "#F0E442", "#0072B2", "#D55E00", "#CC79A7")
# To use for line and point colors, add
sound_traj +
scale_colour_manual(values = cbbPalette[c(3, 7, 8)])
```
## Repel labels
```{r}
library(ggrepel)
sounds <- sounds %>%
mutate(label = case_when(
age == max(age) ~ sound))
ggplot(sounds, aes(x = age,
y = prop_produce,
color = fct_reorder2(sound, age, prop_produce))) +
geom_smooth(se = FALSE, lwd = .5) +
geom_point(size = 2) +
labs(x = "Age (months)",
y = "Proportion of Children Producing") +
geom_text_repel(aes(label = label),
nudge_x = 1,
direction = "y",
na.rm = TRUE) +
guides(color = FALSE)
```
# Continuous colors
*N.B. All of the example plots below are great examples of how **not** to use continuous colors. I'm showing these so you can see how to work with continuous color palettes, and to make this topic flow easier for you I'm sticking with original dataset.*
## Default continuous palette
Let’s map color to a continuous variable. For this, we are returning to `geom_line` instead of `geom_smooth`, because the latter doesn't respond to continuous color palettes.
```{r}
sound_by_age <- ggplot(sounds, aes(x = age,
y = prop_produce,
color = age)) +
geom_line(aes(group = sound), lwd = .5) +
geom_point(size = 2) +
labs(x = "Age (months)",
y = "Proportion of Children Producing")
sound_by_age
```
## Color choice with continuous variables
With discrete colors, we used either `scale_color_manual` or `scale_fill_manual` (and sometimes both were needed!). For continuous colors, we use either `scale_color_gradient` or `scale_fill_gradient`.
```{r}
sound_by_age +
scale_color_gradient()
```
You can reverse the gradient scale...
```{r}
sound_by_age +
scale_color_gradient(trans = "reverse")
```
```{r}
sound_by_age +
scale_color_gradient(low = "white", high = "red")
```
We can make this same plot using a custom greyscale gradient.
```{r}
sound_by_age +
scale_color_gradient(low = "grey90", high = "black")
```
So `scale_color_gradient` gives you a sequential gradient, but you may want a diverging color scheme instead. For that, you can use `scale_color_gradient2`
```{r}
# Diverging color scheme
med_age <- sounds %>%
summarize(mos = median(age)) %>%
pull()
sound_by_age +
scale_color_gradient2(midpoint = med_age,
low="blue", mid="white", high="red" )
```
## Built-in continuous palettes
### Use `RColorBrewer`
Again, to use you need to install and load the `RColorBrewer` palette.
```{r eval = FALSE}
library(RColorBrewer)
```
Then use `scale_color_gradientn`.
```{r}
sound_by_age +
scale_color_gradientn(colours = brewer.pal(n=5, name="PuBuGn"))
```
Reverse the colors...
```{r}
sound_by_age +
scale_color_gradientn(colours = rev(brewer.pal(n=5, name="PuBuGn")))
```
### Viridis
Read more here in the [viridis vignette](https://cran.r-project.org/web/packages/viridis/vignettes/intro-to-viridis.html)
```{r eval = FALSE}
library(viridis)
```
The default is the `viridis` palette within the `viridis` package!
Note! For discrete == FALSE (the default) all other arguments are as to `scale_fill_gradientn` or `scale_color_gradientn`.
```{r}
sound_by_age +
scale_color_viridis()
```
```{r}
sound_by_age +
scale_color_viridis(option = "magma")
```
Read the help function for `?scale_color_viridis`. We'll use the "inferno" palette _in reverse_.
```{r}
sound_by_age +
scale_color_viridis(option = "inferno", begin = 1, end = 0)
```
# Final challenge (#10)
<div class="panel panel-success">
<div class="panel-heading">Challenge #10:</div>
<div class="panel-body">
Using new data, make three new plots. Use any `geom` that makes sense. The plots should:
- Have x- and y-axes that are each quantitative variables.
- Apply a non-default color palette, either coloring by a qualitative variable (discrete colors) or a quantitative variable (continuous colors). This list of [R color palettes](https://github.com/EmilHvitfeldt/r-color-palettes) has even more ideas than we could cover in class.
1. In the first plot, you must **wield color carefully and effectively**. The addition of the color/fill aesthetics must be done in a way that the interpretation of the plot improves. Also, you must show how your colors fare for colorblind viewers. Include 2-3 sentences about why you made the plot that you did. What questions does your plot answers (or perhaps what questions does your plot raise)?
2. In the second plot, you must **make a greyscale version of your first plot!** And again, it must look good and make sense.
3. In the third plot, you must **use color badly**. Make a plot where the colors are either redundant, confusing, or just generally non-sensical. Explain why this last visualization fails.
</div>
</div>
Some data ideas:
- MacArthur-Bates Communicative Development Inventory (MB-CDI), a family of parent-report questionnaires measuring children's vocabulary understanding and production
- [R package `wordbankr`](https://cran.r-project.org/web/packages/wordbankr/index.html)
- See my code [here](03a-meow-cleaning.html)
- POTUS Executive Orders
- [Data](https://www.federalregister.gov/executive-orders)
- Follow Bob Rudis' code-through [here](https://rud.is/b/2018/04/18/examining-potus-executive-orders/)
- National Electronic Injury Surveillance System (NEISS)
- [R package `neiss`](https://github.com/hadley/neiss)
- Follow Julia Silge's code-through [here](https://juliasilge.com/blog/your-floor/)
- Flights
- [R package `pnwflights14`](https://github.com/ismayc/pnwflights14)
- [R package `nycflights13`](https://github.com/hadley/nycflights13)
- Building Permits
- See code [here](https://github.com/hadley/building-permits)
- Watch YouTube code-through [here](https://www.youtube.com/watch?v=go5Au01Jrvs)
- Cocktail Balance
- [Data](https://github.com/karnesky/cocktail-balance)
- NASA Weather
- [Data](https://github.com/hadley/nasaweather)
- Social Security Administration Baby Names
- [R package `babynames`](https://cran.r-project.org/web/packages/babynames/index.html)
- Follow Julia Silge *'My Baby Boomer Name Might Have Been "Debbie"'*: https://juliasilge.com/blog/my-baby-boomer-name/
- Follow Hilary Parker: *Hilary: The Most Poisoned Baby Name in US History*: https://hilaryparker.com/2013/01/30/hilary-the-most-poisoned-baby-name-in-us-history/
- Youth Behavior Risk Surveillance System
- [R package `yrbss`](https://github.com/hadley/yrbss)
- Some [good ideas here](https://www.cdc.gov/nchhstp/newsroom/2012/yrbs-graphics2012.html)
- Gun sales
- [Data](https://github.com/hadley/gun-sales)
- Some [example plots here](https://github.com/NYTimes/gunsales/blob/master/out/plots.pdf)
- Gapminder
- [R package `gapminder`](https://cran.r-project.org/web/packages/gapminder/index.html)
- Some [example plots here](https://github.com/jennybc/ggplot2-tutorial/blob/master/gapminder-ggplot2-scatterplot.md)