-
Notifications
You must be signed in to change notification settings - Fork 3
/
data-viz.qmd
1661 lines (1464 loc) · 51.8 KB
/
data-viz.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Principles of Data Visualization {#sec-data-viz-chapter}
```{r}
library(tidyverse)
library(lubridate)
library(gapminder)
library(tidyverse)
library(lubridate)
library(sf)
library(albersusa)
library(colorspace)
library(shades)
library(scales)
library(knitr)
library(patchwork)
library(ggpubr)
## Color palette hubs
greys <- c(0, 60, 40, 60, 0, 40, 60, 0)
pal1 <- paste0("grey", greys)
## Set up hubs map
hub_northwest <- c("AK", "OR", "ID", "WA")
hub_california <- "CA"
hub_southwest <- c("AZ", "HI", "NM", "NV", "UT")
hub_northern_plains <- c("CO", "MT", "ND", "NE", "SD", "WY")
hub_southern_plains <- c("KS", "OK", "TX")
hub_midwest <- c("IL", "IN", "MN", "IA", "MI", "MO", "OH", "WI")
hub_southeast <- c("AL", "AR", "LA", "MS", "TN", "KY", "GA", "NC", "FL", "GA", "SC", "VA")
hub_northeast <- c("CT", "DE", "ME", "MA", "MD", "NH", "NJ", "NY", "PA", "RI", "VT", "WV")
hubs_order <- c(
"Northwest",
"California",
"Southwest",
"Northern Plains",
"Southern Plains",
"Midwest",
"Southeast",
"Northeast"
)
## Read in DroughMonitor hub data
dm_perc_cat_hubs_raw <- rio::import(here::here("data", "dm_export_20000101_20210909_perc_cat_hubs.json"))
## Wrangle
dm_perc_cat_hubs <-
dm_perc_cat_hubs_raw %>%
## Remove Northern Forest as it combines Midwest + Northeast
filter(Name != "Northern Forests\\n") %>%
## Remove Carribean which shows no distinct drought patterns anyway
filter(Name != "Caribbean") %>%
mutate(
across(c(MapDate, ValidStart, ValidEnd), as_date),
across(None:D4, ~ as.numeric(.x) / 100),
Name = stringr::str_remove(Name, "\\\\n"),
Name = str_replace(Name, "Nothern", "Northern")
) %>%
rename("date" = "MapDate", "hub" = "Name") %>%
pivot_longer(
cols = c(None:D4),
names_to = "category",
values_to = "percentage"
) %>%
filter(category != "None") %>%
mutate(category = factor(category)) %>%
dplyr::select(-ValidStart, -ValidEnd, -StatisticFormatID) %>%
mutate(
year = year(date),
week = week(date),
hub = factor(hub, levels = hubs_order, labels = hubs_order)
) %>%
group_by(year) %>%
mutate(max_week = max(week)) %>% ## for var
ungroup() %>%
filter(percentage > 0)
dm_perc_cat_hubs |>
jsonlite::write_json(path = "data/dm_perc_cat_hubs.json")
```
```{r}
i <- 1
chapter_number <- 2
source("_common.R")
```
In the spring of 2021, nearly all of the American West was in a drought. Officials in Southern California declared a water emergency in April, citing unprecedented conditions. This probably didn’t come as news to residents of California and other western states. Drought conditions like those in the West in 2021 are becoming increasingly common, yet communicating the extent of the problem remains difficult. How can this data be presented in a way that is both accurate and compelling enough to get people to take notice?
Data visualization designers Cédric Scherer and Georgios Karamanis took on this challenge in the fall of 2021 to create a graph of US drought conditions over the last two decades for the magazine Scientific American. They turned to the ggplot2 package to transform dry data (pardon the pun) from the National Drought Center into a visually arresting and impactful visualization.
This chapter delves into why the data visualization that Scherer and Karamanis created is effective and introduces you to the grammar of graphics, a theory to make sense of graphs that underlies the ggplot2 package. You’ll then learn how to use ggplot2 by re-creating the drought graph step-by-step. In the process, I’ll highlight some key principles of high-quality data visualization that you can use to improve your own work.
## The Drought Visualization
Other news organizations had relied on the same National Drought Center data in their stories, but Scherer and Karamanis visualized it so that it both grabs attention and communicates the scale of the phenomenon. @fig-final-viz shows a section of the final visualization (due to space constraints, I could include only four regions). The graph makes apparent the increase in drought conditions over the last two decades, especially in California and the Southwest.
To understand why this visualization is effective, let’s break it down.
At the broadest level, the data visualization is notable for its minimalist aesthetic. For example, there are no grid lines and few text labels, as well as minimal text along the axes. Scherer and Karamanis removed what statistician Edward Tufte, in his 1983 book *The Visual Display of Quantitative Information* (Graphics Press), calls *chartjunk*. Tufte wrote that extraneous elements often hinder, rather than help, our understanding of charts (and researchers and data visualization designers have generally agreed).
Need proof that Scherer and Karamanis’s decluttered graph is better than the alternative? @fig-cluttered-viz shows a version with a few tweaks to the code to include grid lines and text labels on axes.
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-final-viz
#| fig-height: 8
#| fig-cap: "A section of the final drought visualization, with a few tweaks made to fit this book"
dm_perc_cat_hubs %>%
filter(hub %in% c(
"Northwest",
"California",
"Southwest",
"Northern Plains"
)) %>%
ggplot(aes(
x = week,
y = percentage
)) +
geom_rect(
aes(
xmin = .5,
xmax = max_week + .5,
ymin = -0.005,
ymax = 1
),
fill = "#f4f4f9",
color = NA,
size = 0.4,
show.legend = FALSE
) +
geom_col(
aes(
fill = category,
fill = after_scale(addmix(
darken(fill, .05, space = "HLS"),
"#d8005a",
.15
)),
color = after_scale(darken(fill, .2, space = "HLS"))
),
width = .9,
size = 0.12
) +
facet_grid(
rows = vars(year),
cols = vars(hub),
switch = "y"
) +
coord_cartesian(clip = "off") +
scale_x_continuous(
expand = c(.02, .02),
guide = "none",
name = NULL
) +
scale_y_continuous(
expand = c(0, 0),
position = "right",
labels = NULL,
name = NULL
) +
scale_fill_viridis_d(
option = "rocket",
name = NULL,
direction = -1,
begin = .17,
end = .97,
labels = c(
"Abnormally Dry",
"Moderate Drought",
"Severe Drought",
"Extreme Drought",
"Exceptional Drought"
)
) +
guides(fill = guide_legend(
nrow = 2,
override.aes = list(size = 1)
)) +
theme_light(base_family = "Roboto") +
theme(
axis.title = element_text(
size = 14,
color = "black"
),
axis.text = element_text(
family = "Roboto Mono",
size = 11
),
axis.line.x = element_blank(),
axis.line.y = element_line(
color = "black",
size = .2
),
axis.ticks.y = element_line(
color = "black",
size = .2
),
axis.ticks.length.y = unit(2, "mm"),
legend.position = "top",
legend.title = element_text(
color = "#2DAADA",
face = "bold"
),
legend.text = element_text(color = "#2DAADA"),
strip.text.x = element_text(
hjust = .5,
face = "plain",
color = "black",
margin = margin(t = 20, b = 5)
),
strip.text.y.left = element_text(
angle = 0,
vjust = .5,
face = "plain",
color = "black"
),
strip.background = element_rect(
fill = "transparent",
color = "transparent"
),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.spacing.x = unit(0.3, "lines"),
panel.spacing.y = unit(0.25, "lines"),
panel.background = element_rect(
fill = "transparent",
color = "transparent"
),
panel.border = element_rect(
color = "transparent",
size = 0
),
plot.background = element_rect(
fill = "transparent",
color = "transparent",
size = .4
),
plot.margin = margin(rep(18, 4))
)
```
```{r}
#| results: asis
save_figure_for_nostarch(figure_height = 8)
```
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-cluttered-viz
#| fig-height: 8
#| fig-cap: "The cluttered version of the drought visualization"
dm_perc_cat_hubs %>%
filter(hub %in% c(
"Northwest",
"California",
"Southwest",
"Northern Plains"
)) %>%
ggplot(aes(
x = week,
y = percentage
)) +
# geom_rect(
# aes(
# xmin = .5,
# xmax = max_week + .5,
# ymin = -0.005,
# ymax = 1
# ),
# fill = "#f4f4f9",
# color = NA,
# size = 0.4,
# show.legend = FALSE
# ) +
geom_col(
aes(
fill = category,
fill = after_scale(addmix(
darken(fill, .05, space = "HLS"),
"#d8005a",
.15
)),
color = after_scale(darken(fill, .2, space = "HLS"))
),
width = .9,
size = 0.12
) +
facet_grid(
rows = vars(year),
cols = vars(hub),
switch = "y"
) +
coord_cartesian(clip = "off") +
scale_x_continuous(
expand = c(.02, .02),
guide = "none",
name = NULL
) +
scale_y_continuous(
expand = c(0, 0),
position = "right",
labels = percent_format(),
name = NULL
) +
scale_fill_viridis_d(
option = "rocket",
name = NULL,
direction = -1,
begin = .17,
end = .97,
labels = c(
"Abnormally Dry",
"Moderate Drought",
"Severe Drought",
"Extreme Drought",
"Exceptional Drought"
)
) +
guides(fill = guide_legend(
nrow = 2,
override.aes = list(size = 1)
)) +
theme_light(base_family = "Roboto") +
theme(
axis.title = element_text(
size = 14,
color = "black"
),
axis.text = element_text(family = "Roboto Mono"),
axis.line.x = element_blank(),
axis.line.y = element_line(
color = "black",
size = .2
),
axis.ticks.y = element_line(
color = "black",
size = .2
),
axis.ticks.length.y = unit(2, "mm"),
legend.position = "top",
legend.title = element_text(
color = "#2DAADA",
face = "bold"
),
legend.text = element_text(color = "#2DAADA"),
strip.text.x = element_text(
hjust = .5,
face = "plain",
color = "black",
margin = margin(t = 20, b = 5)
),
strip.text.y.left = element_text(
angle = 0,
vjust = .5,
face = "plain",
color = "black"
),
strip.background = element_rect(
fill = "transparent",
color = "transparent"
),
# panel.grid.minor = element_blank(),
# panel.grid.major = element_blank(),
panel.spacing.x = unit(0.3, "lines"),
panel.spacing.y = unit(0.25, "lines"),
panel.background = element_rect(
fill = "transparent",
color = "transparent"
),
panel.border = element_rect(
color = "transparent",
size = 0
),
plot.background = element_rect(
fill = "transparent",
color = "transparent",
size = .4
),
plot.margin = margin(rep(18, 4))
)
```
```{r}
#| results: asis
save_figure_for_nostarch(figure_height = 8)
```
It’s not just that this cluttered version looks worse; the clutter actively inhibits understanding. Rather than focusing on overall drought patterns (the point of the graph), our brains get stuck reading repetitive and unnecessary axis text.
One of the best ways to reduce clutter is to break a single chart into a set of component charts, as Scherer and Karamanis have done (this approach, known as *faceting*, will be discussed further in @sec-faceting-the-plot). Each rectangle represents one region in one year. Filtering the larger chart to show the Southwest region in 2003 produces the graph shown in @fig-viz-sw-2003, where the x-axis indicates the week and the y-axis indicates the percentage of that region at different drought levels.
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-viz-sw-2003
#| fig-height: 4
#| fig-cap: "A drought visualization for the Southwest in 2003"
dm_perc_cat_hubs %>%
filter(hub == "Southwest") %>%
filter(year == 2003) %>%
ggplot(aes(
x = week,
y = percentage
)) +
geom_rect(
aes(
xmin = .5,
xmax = max_week + .5,
ymin = -0.005,
ymax = 1
),
fill = "#f4f4f9",
color = NA,
size = 0.4,
show.legend = FALSE
) +
geom_col(
aes(
fill = category,
fill = after_scale(addmix(
darken(fill, .05, space = "HLS"),
"#d8005a",
.15
)),
color = after_scale(darken(fill, .2, space = "HLS"))
),
width = .9,
size = 0.12
) +
facet_grid(
rows = vars(year),
cols = vars(hub),
switch = "y"
) +
coord_cartesian(clip = "off") +
scale_x_continuous(
expand = c(.02, .02),
guide = "none",
name = NULL
) +
scale_y_continuous(
expand = c(0, 0),
position = "right",
labels = NULL,
name = NULL
) +
scale_fill_viridis_d(
option = "rocket",
name = NULL,
direction = -1,
begin = .17,
end = .97,
labels = c(
"Abnormally Dry",
"Moderate Drought",
"Severe Drought",
"Extreme Drought",
"Exceptional Drought"
)
) +
guides(fill = guide_legend(
nrow = 2,
override.aes = list(size = 1)
)) +
theme_light(base_family = "Roboto") +
theme(
axis.title = element_text(
size = 14,
color = "black"
),
axis.text = element_text(
family = "Roboto Mono",
size = 11
),
axis.line.x = element_blank(),
axis.line.y = element_line(
color = "black",
size = .2
),
axis.ticks.y = element_line(
color = "black",
size = .2
),
axis.ticks.length.y = unit(2, "mm"),
legend.position = "none",
legend.title = element_text(
color = "#2DAADA",
face = "bold"
),
legend.text = element_text(color = "#2DAADA"),
strip.text.x = element_text(
hjust = .5,
face = "plain",
color = "black",
margin = margin(t = 20, b = 5)
),
strip.text.y.left = element_text(
angle = 0,
vjust = .5,
face = "plain",
color = "black"
),
strip.background = element_rect(
fill = "transparent",
color = "transparent"
),
panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.spacing.x = unit(0.3, "lines"),
panel.spacing.y = unit(0.25, "lines"),
panel.background = element_rect(
fill = "transparent",
color = "transparent"
),
panel.border = element_rect(
color = "transparent",
size = 0
),
plot.background = element_rect(
fill = "transparent",
color = "transparent",
size = .4
),
plot.margin = margin(rep(18, 4))
)
```
```{r}
#| results: asis
save_figure_for_nostarch(figure_height = 4)
```
Zooming in on a single region in a single year also makes the color choices more obvious. The lightest orange bars show the percentage of the region that is abnormally dry, and the darkest purple bars show the percentage experiencing exceptional drought conditions. As you’ll see shortly, this range of colors was intentionally chosen to make differences in the drought levels visible to all readers.
Despite the graph’s complexity, the R code that Scherer and Karamanis wrote to produce it is relatively simple, due largely to a theory called the *grammar of graphics*.
## The Grammar of Graphics
When working in Excel, you begin by selecting the type of graph you want
to make. Need a bar chart? Click the bar chart icon. Need a line chart? Click the line chart icon. If you’ve only ever made charts in Excel, this first step may seem so obvious that you’ve never even given the data visualization process much thought, but in fact there are many ways to think about graphs. For example, rather than thinking of graph types as distinct, we can recognize and use their commonalities as the starting point for making them.
This approach to thinking about graphs comes from the late statistician Leland Wilkinson. For years, Wilkinson thought deeply about what data visualization is and how we can describe it. In 1999 he published a book called *The Grammar of Graphics* (Springer) that sought to develop a consistent way of describing all graphs. In it, Wilkinson argued that we should think of plots not as distinct types, à la Excel, but as following a grammar that we can use to describe any plot. Just as English grammar tells us that a noun is typically followed by a verb (which is why “he goes” works, while the opposite, “goes he,” does not), the grammar of graphics helps us understand why certain graph types “work.”
Thinking about data visualization through the lens of the grammar of graphics helps highlight, for example, that graphs typically have some data that is plotted on the x-axis and other data that is plotted on the y-axis. This is the case whether the graph is a bar chart or a line chart, as @fig-bar-line-chart shows.
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-bar-line-chart
#| fig-cap: "A bar chart and a line chart showing identical data"
gapminder_10_rows <- gapminder %>%
slice(1:10)
bar_chart <- ggplot(
data = gapminder_10_rows,
mapping = aes(
x = year,
y = lifeExp
)
) +
geom_col() +
scale_y_continuous(limits = c(0, 45)) +
scale_x_continuous(limits = c(1950, 2000))
line_chart <- ggplot(
data = gapminder_10_rows,
mapping = aes(
x = year,
y = lifeExp
)
) +
geom_line() +
scale_y_continuous(limits = c(0, 45)) +
scale_x_continuous(limits = c(1950, 2000))
bar_chart + line_chart +
plot_annotation(
title = "Life Expectancy in Afghanistan, 1952-1997",
caption = "Data from Gapminder Foundation"
) &
theme_minimal() +
theme(
axis.title = element_blank(),
axis.text = element_text(),
plot.title = element_text(
face = "bold",
hjust = 0.5,
size = 14
),
plot.caption = element_text(
color = "grey40",
size = 10
)
)
```
```{r}
#| results: asis
save_figure_for_nostarch()
```
While the graphs look different (and would, to the Excel user, be different types of graphs), Wilkinson’s grammar of graphics emphasizes their similarities. (Incidentally, Wilkinson’s feelings on graph-making tools like Excel became clear when he wrote that “most charting packages channel user requests into a rigid array of chart types.”)
When Wilkinson wrote his book, no data visualization tool could implement his grammar of graphics. This would change in 2010, when Hadley Wickham announced the `ggplot2` package for R in the article “A Layered Grammar of Graphics,” published in the *Journal of Computational and Graphical Statistics*. By providing the tools to implement Wilkinson’s ideas, ggplot2 would come to revolutionize the world of data visualization.
## Working With ggplot2
The `ggplot2` R package (which I, like nearly everyone in the data visualization world, will refer to simply as *ggplot*) relies on the idea of plots having multiple layers. This section will walk you through some of the most important ones. You’ll begin by selecting variables to map to aesthetic properties. Then you’ll choose a geometric object to use to represent your data. Next, you’ll change the aesthetic properties of your chart (its color scheme, for example) using a scale_ function. Finally, you’ll use a `theme_` function to set the overall look and feel of your plot.
### Mapping Data to Aesthetic Properties
To create a graph with ggplot, you begin by mapping data to aesthetic properties. All this really means is that you use elements like the x- or y-axis, color, and size (the so-called *aesthetic properties*) to represent variables. You’ll use the data on life expectancy in Afghanistan, introduced in @fig-bar-line-chart, to generate a plot. To access this data, enter the following code:
```{r}
#| echo: true
library(tidyverse)
gapminder_10_rows <- read_csv("https://data.rfortherestofus.com/gapminder_10_rows.csv")
```
This code first loads the `tidyverse` package, introduced in @sec-crash-course-chapter, and then uses the `read_csv()` function to access data from the book’s website and assign it to the `gapminder_10_rows` object.
The resulting `gapminder_10_rows` tibble looks like this:
```{r}
gapminder_10_rows
```
This output is a shortened version of the full which includes over 1,700 rows of data.
Before making a chart with ggplot, you need to decide which variable to put on the x-axis and which to put on the y-axis. For data showing change over time, it’s common to put the date (in this case, `year`) on the x-axis and the changing value (in this case, `lifeExp`) on the y-axis. To do so, define the `ggplot()` function as follows:
```{r}
#| label: blank-ggplot
#| echo: true
#| eval: false
ggplot(
data = gapminder_10_rows,
mapping = aes(
x = year,
y = lifeExp
)
)
```
This function contains numerous arguments. Each argument goes on its own line, for the sake of readability, separated by commas. The `data` argument tells R to use the data frame gapminder_10_rows, and the `mapping` argument maps `year` to the x-axis and `lifeExp` to the y-axis.
Running this code produces the chart in @fig-blank-ggplot, which doesn’t look like much yet.
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| ref-label: blank-ggplot
#| label: fig-blank-ggplot
#| fig-cap: "A blank chart that maps year values to the x-axis and life expectancy values to the y-axis"
```
```{r}
#| results: asis
save_figure_for_nostarch()
```
Notice that the x-axis corresponds to year and the y-axis corresponds to `lifeExp`, and the values on both axes match the scope of the data. In the `gapminder_10_rows` data frame, the first year is 1952 and the last year is 1997. The range of the x-axis has been created with this data in mind. Likewise, the values for `lifeExp`, which go from about 28 to about 42, will fit nicely on the y-axis.
### Choosing the Geometric Objects
Axes are nice, but the graph is missing any type of visual representation of the data. To get this, you need to add the next ggplot layer: geoms. Short for *geometric objects*, *geoms* are functions that provide different ways of representing data. For example, to add points to the graph, you use `geom_point()`:
```{r}
#| label: gapminder-points
#| echo: true
#| eval: false
ggplot(
data = gapminder_10_rows,
mapping = aes(
x = year,
y = lifeExp
)
) +
geom_point()
```
Now the graph shows that people in 1952 had a life expectancy of about 28 and that this value rose every year in the dataset (see @fig-gapminder-points-plot).
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-gapminder-points-plot
#| ref-label: gapminder-points
#| fig-cap: "The life expectancy chart with points added"
```
```{r}
#| results: asis
save_figure_for_nostarch()
```
Say you change your mind and want to make a line chart instead. All you have to do is replace `geom_point()` with `geom_line()` like so:
```{r}
#| label: gapminder-line
#| echo: true
#| eval: false
ggplot(
data = gapminder_10_rows,
mapping = aes(
x = year,
y = lifeExp
)
) +
geom_line()
```
@fig-gapminder-line-plot shows the result.
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-gapminder-line-plot
#| ref-label: gapminder-line
#| fig-cap: "The data as a line chart"
```
```{r}
#| results: asis
save_figure_for_nostarch()
```
To really get fancy, you could add both `geom_point()` and `geom_line()` as follows:
```{r}
#| label: gapminder-points-line
#| echo: true
#| eval: false
ggplot(
data = gapminder_10_rows,
mapping = aes(
x = year,
y = lifeExp
)
) +
geom_point() +
geom_line()
```
This code generates a line chart with points, as shown in @fig-gapminder-points-line-plot.
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-gapminder-points-line-plot
#| ref-label: gapminder-points-line
#| fig-cap: "The same data with both points and a line"
```
```{r}
#| results: asis
save_figure_for_nostarch()
```
You can swap in `geom_col()` to create a bar chart:
```{r}
#| label: gapminder-bar
#| echo: true
#| eval: false
ggplot(
data = gapminder_10_rows,
mapping = aes(
x = year,
y = lifeExp
)
) +
geom_col()
```
Notice in @fig-gapminder-bar-plot that the y-axis range has been automatically updated, going from 0 to 40 to account for the different geom.
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-gapminder-bar-plot
#| ref-label: gapminder-bar
#| eval: true
#| fig-cap: "The life expectancy data as a bar chart"
```
```{r}
#| results: asis
save_figure_for_nostarch()
```
As you can see, the difference between a line chart and a bar chart isn’t as great as the Excel chart-type picker might have you believe. Both can have the same underlying properties (namely, years on the x-axis and life expectancies on the y-axis). They simply use different geometric objects to visually represent the data.
Many geoms are built into ggplot. In addition to `geom_bar()`, `geom_point()`, and `geom_line()`, the geoms `geom_histogram()`, `geom_boxplot()`, and `geom_area()` are among the most commonly used. To see all geoms, visit the ggplot documentation website at <https://ggplot2.tidyverse.org/reference/index.html#geoms>.
### Altering Aesthetic Properties
Before we return to the drought data visualization, let’s look at a few additional layers you can use to alter the bar chart. Say you want to change the color of the bars. In the grammar of graphics approach to chart-making, this means mapping some variable to the aesthetic property of `fill`. (For a bar chart, the aesthetic property of color would change only the outline of each bar.) In the same way that you mapped `year` to the x-axis and `lifeExp` to the y-axis, you can map fill to a variable, such as `year`:
```{r}
#| label: gapminder-bar-colors
#| echo: true
#| eval: false
ggplot(
data = gapminder_10_rows,
mapping = aes(
x = year,
y = lifeExp,
fill = year
)
) +
geom_col()
```
@fig-gapminder-bar-colors-plot shows the result. Now the fill is darker for earlier years and lighter for later years (as also indicated by the legend, added to the right of the plot).
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-gapminder-bar-colors-plot
#| ref-label: gapminder-bar-colors
#| fig-cap: "The same chart, now with added colors"
```
```{r}
#| results: asis
save_figure_for_nostarch()
```
To change the fill colors, use a new scale layer with the `scale_fill _viridis_c()` function (the `c` at the end of the function name refers to the fact that the data is continuous, meaning it can take any numeric value):
```{r gapminder-viridis, echo = TRUE, eval = FALSE}
ggplot(
data = gapminder_10_rows,
mapping = aes(
x = year,
y = lifeExp,
fill = year
)
) +
geom_col() +
scale_fill_viridis_c()
```
This function changes the default palette to one that is colorblind-friendly and prints well in grayscale. The `scale_fill_viridis_c()` function is just one of many that start with scale_ and can alter the fill scale. Chapter 11 of *ggplot2: Elegant Graphics for Data Analysis*, 3rd edition, discusses various color and fill scales. You can read it online at <https://ggplot2-book.org/scales-colour.html>.
### The Fourth Layer: Setting a Theme
The final layer we’ll look at is the theme layer, which allows you to change the overall look and feel of your plots (including their background and grid lines). As with the `scale_` functions, a number of functions also start with `theme_`. Add `theme_minimal()` as follows:
```{r}
#| label: gapminder-theme
#| echo: true
#| eval: false
ggplot(
data = gapminder_10_rows,
mapping = aes(
x = year,
y = lifeExp,
fill = year
)
) +
geom_col() +
scale_fill_viridis_c() +
theme_minimal()
```
This theme starts to declutter the plot, as you can see in @fig-gapminder-theme-plot.
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-gapminder-theme-plot
#| ref-label: gapminder-theme
#| fig-cap: "The same chart with `theme_minimal()` added"
```
```{r}
#| results: asis
save_figure_for_nostarch()
```
By now, you should see why Hadley Wickham described the `ggplot2` package as using a layered grammar of graphics. It implements Wilkinson’s theory by creating multiple layers: first, variables to map to aesthetic properties; second, geoms to represent the data; third, the `scale_` function to adjust aesthetic properties; and finally, the `theme_` function to set the plot’s overall look and feel.
You could still improve this plot in many ways, but instead let’s return to the drought data visualization by Scherer and Karamanis. By walking through their code, you’ll learn about making high-quality data visualization with ggplot and R.
## Recreating the Drought Visualization with ggplot
The drought visualization code relies on a combination of ggplot fundamentals and some lesser-known tweaks that make it really shine. To understand how Scherer and Karamanis made their data visualization, we’ll start with a simplified version of their code, then build it up layer by layer, adding elements as we go.
First, you’ll import the data. Scherer and Karamanis did a bunch of data wrangling on the raw data, but I’ve saved the simplified output for you. Because it’s in JavaScript Object Notation (JSON) format, Scherer and Karamanis use the `import()` function from the `rio` package, which simplifies the process of importing JSON data:
```{r echo = TRUE}
library(rio)
ddm_perc_cat_hubs <- import("https://data.rfortherestofus.com/dm_perc_cat_hubs.json")
```
*JSON* is a common format for data used in web applications, though it’s far less common in R, where it can be complicated to work with. Luckily, the `rio` package simplifies its import.
### Plotting One Region and Year
Scherer and Karamanis’s final plot consists of many years and regions. To see how they created it, we’ll start by looking at just the Southwest region in 2003.
First, you need to create a data frame. You’ll use the `filter()` function twice: the first time to keep only data for the Southwest region, and the second time to keep only data from 2003. In both cases, you use the following syntax:
```{r}
#| echo: true
#| eval: false
filter(variable_name == value)
```
This tells R to keep only observations where variable_name is equal to some value. The code starts with the `dm_perc_cat_hubs_raw` data frame before filtering it and then saving it as a new object called `southwest_2003`:
```{r}
#| echo: true
southwest_2003 <- dm_perc_cat_hubs %>%
filter(hub == "Southwest") %>%
filter(year == 2003)
```
To take a look at this object and see the variables you have to work with, enter `southwest_2003` in the console, which should return this output:
```{r}
southwest_2003
```
The date variable represents the start date of the week in which the observation took place. The hub variable is the region, and category is the level of drought: a value of `D0` indicates the lowest level of drought, while `D5` indicates the highest level. The `percentage` variable is the percentage of that region in that drought category, ranging from 0 to 1. The `year` and `week` variables are the observation year and week number (beginning with week 1). The `max_week` variable is the maximum number of weeks in a given year.
Now you can use this southwest_2003 object for your plot:
```{r}
#| label: southwest-2003-no-style
#| echo: true
#| eval: false
ggplot(
data = southwest_2003,
aes(
x = week,
y = percentage,
fill = category
)
) +
geom_col()
```
The ggplot() function tells R to put `week` on the x-axis and `percentage` on the y-axis, as well as to use the category variable for the `fill` color. The `geom_col()` function creates a bar chart in which each bar’s fill color represents the percentage of the region at each drought level for that particular week, as shown in @fig-southwest-2003-no-style-plot.
```{r}
#| results: asis
print_nostarch_file_name()
```
```{r}
#| label: fig-southwest-2003-no-style-plot
#| ref-label: southwest-2003-no-style
#| fig-cap: "One year (2003) and region (Southwest) of the drought visualization"