-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathtemp_book.tex
5083 lines (3929 loc) · 192 KB
/
temp_book.tex
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
% Options for packages loaded elsewhere
\PassOptionsToPackage{unicode}{hyperref}
\PassOptionsToPackage{hyphens}{url}
\PassOptionsToPackage{dvipsnames,svgnames,x11names}{xcolor}
%
\documentclass[
letterpaper,
DIV=11,
numbers=noendperiod]{scrreprt}
\usepackage{amsmath,amssymb}
\usepackage{iftex}
\ifPDFTeX
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{textcomp} % provide euro and other symbols
\else % if luatex or xetex
\usepackage{unicode-math}
\defaultfontfeatures{Scale=MatchLowercase}
\defaultfontfeatures[\rmfamily]{Ligatures=TeX,Scale=1}
\fi
\usepackage{lmodern}
\ifPDFTeX\else
% xetex/luatex font selection
\fi
% Use upquote if available, for straight quotes in verbatim environments
\IfFileExists{upquote.sty}{\usepackage{upquote}}{}
\IfFileExists{microtype.sty}{% use microtype if available
\usepackage[]{microtype}
\UseMicrotypeSet[protrusion]{basicmath} % disable protrusion for tt fonts
}{}
\makeatletter
\@ifundefined{KOMAClassName}{% if non-KOMA class
\IfFileExists{parskip.sty}{%
\usepackage{parskip}
}{% else
\setlength{\parindent}{0pt}
\setlength{\parskip}{6pt plus 2pt minus 1pt}}
}{% if KOMA class
\KOMAoptions{parskip=half}}
\makeatother
\usepackage{xcolor}
\setlength{\emergencystretch}{3em} % prevent overfull lines
\setcounter{secnumdepth}{5}
% Make \paragraph and \subparagraph free-standing
\ifx\paragraph\undefined\else
\let\oldparagraph\paragraph
\renewcommand{\paragraph}[1]{\oldparagraph{#1}\mbox{}}
\fi
\ifx\subparagraph\undefined\else
\let\oldsubparagraph\subparagraph
\renewcommand{\subparagraph}[1]{\oldsubparagraph{#1}\mbox{}}
\fi
\usepackage{color}
\usepackage{fancyvrb}
\newcommand{\VerbBar}{|}
\newcommand{\VERB}{\Verb[commandchars=\\\{\}]}
\DefineVerbatimEnvironment{Highlighting}{Verbatim}{commandchars=\\\{\}}
% Add ',fontsize=\small' for more characters per line
\usepackage{framed}
\definecolor{shadecolor}{RGB}{241,243,245}
\newenvironment{Shaded}{\begin{snugshade}}{\end{snugshade}}
\newcommand{\AlertTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\AnnotationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\AttributeTok}[1]{\textcolor[rgb]{0.40,0.45,0.13}{#1}}
\newcommand{\BaseNTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\BuiltInTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\CharTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\CommentTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\CommentVarTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\newcommand{\ConstantTok}[1]{\textcolor[rgb]{0.56,0.35,0.01}{#1}}
\newcommand{\ControlFlowTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\DataTypeTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\DecValTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\DocumentationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\newcommand{\ErrorTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\ExtensionTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\FloatTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\FunctionTok}[1]{\textcolor[rgb]{0.28,0.35,0.67}{#1}}
\newcommand{\ImportTok}[1]{\textcolor[rgb]{0.00,0.46,0.62}{#1}}
\newcommand{\InformationTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\KeywordTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\NormalTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\OperatorTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\OtherTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\PreprocessorTok}[1]{\textcolor[rgb]{0.68,0.00,0.00}{#1}}
\newcommand{\RegionMarkerTok}[1]{\textcolor[rgb]{0.00,0.23,0.31}{#1}}
\newcommand{\SpecialCharTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{#1}}
\newcommand{\SpecialStringTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\StringTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\VariableTok}[1]{\textcolor[rgb]{0.07,0.07,0.07}{#1}}
\newcommand{\VerbatimStringTok}[1]{\textcolor[rgb]{0.13,0.47,0.30}{#1}}
\newcommand{\WarningTok}[1]{\textcolor[rgb]{0.37,0.37,0.37}{\textit{#1}}}
\providecommand{\tightlist}{%
\setlength{\itemsep}{0pt}\setlength{\parskip}{0pt}}\usepackage{longtable,booktabs,array}
\usepackage{calc} % for calculating minipage widths
% Correct order of tables after \paragraph or \subparagraph
\usepackage{etoolbox}
\makeatletter
\patchcmd\longtable{\par}{\if@noskipsec\mbox{}\fi\par}{}{}
\makeatother
% Allow footnotes in longtable head/foot
\IfFileExists{footnotehyper.sty}{\usepackage{footnotehyper}}{\usepackage{footnote}}
\makesavenoteenv{longtable}
\usepackage{graphicx}
\makeatletter
\def\maxwidth{\ifdim\Gin@nat@width>\linewidth\linewidth\else\Gin@nat@width\fi}
\def\maxheight{\ifdim\Gin@nat@height>\textheight\textheight\else\Gin@nat@height\fi}
\makeatother
% Scale images if necessary, so that they will not overflow the page
% margins by default, and it is still possible to overwrite the defaults
% using explicit options in \includegraphics[width, height, ...]{}
\setkeys{Gin}{width=\maxwidth,height=\maxheight,keepaspectratio}
% Set default figure placement to htbp
\makeatletter
\def\fps@figure{htbp}
\makeatother
% load packages
\usepackage{geometry}
\usepackage{xcolor}
\usepackage{eso-pic}
\usepackage{fancyhdr}
\usepackage{sectsty}
\usepackage{fontspec}
\usepackage{titlesec}
%% Set page size with a wider right margin
\geometry{a4paper, total={170mm,257mm}, left=15mm, top=20mm, bottom=25mm, right=25mm}
%% Let's define some colours
\definecolor{light}{HTML}{edf7fa}
\definecolor{highlight}{HTML}{2c6d7d}
\definecolor{dark}{HTML}{336882}
%% Let's add the border on the right hand side
\AddToShipoutPicture{%
\AtPageLowerLeft{%
\put(\LenToUnit{\dimexpr\paperwidth-1.75cm},0){%
\color{light}\rule{3cm}{\LenToUnit\paperheight}%
}%
}%
% logo
% \AtPageLowerLeft{% start the bar at the bottom right of the page
% \put(\LenToUnit{\dimexpr\paperwidth-1.5cm},27.2cm){% move it to the top right
% \color{light}\includegraphics[width=1.2cm]{_extensions/nrennie/PrettyPDF/logo.png}
% }%
% }%
}
%% Style the page number
\fancypagestyle{mystyle}{
% \fancyhf{}
% \renewcommand\headrulewidth{0pt}
% Empty style
}
\pagestyle{mystyle}
% Center align chapter titles
\usepackage{titlesec}
\titleformat{\chapter}[display]
{\normalfont\huge\bfseries\centering\color{dark}}{\chaptertitlename\ \thechapter}{20pt}{\Huge}
% add a border to images
% \let\originalincludegraphics\includegraphics
% \renewcommand{\includegraphics}[2][]{%
% \fcolorbox{light}{white}{\originalincludegraphics[#1]{#2}}%
% }
\let\originalincludegraphics\includegraphics
\renewcommand{\includegraphics}[2][]{%
\setlength{\fboxrule}{4pt} % Set border thickness to 2pt
\fcolorbox{light}{white}{\originalincludegraphics[#1]{#2}}%
}
%% Use some custom fonts
\setsansfont{Ubuntu}[
Path=_extensions/nrennie/PrettyPDF/Ubuntu/,
Scale=0.9,
Extension = .ttf,
UprightFont=*-Regular,
BoldFont=*-Bold,
ItalicFont=*-Italic,
]
\setmainfont{Ubuntu}[
Path=_extensions/nrennie/PrettyPDF/Ubuntu/,
Scale=0.9,
Extension = .ttf,
UprightFont=*-Regular,
BoldFont=*-Bold,
ItalicFont=*-Italic,
]
\KOMAoption{captions}{tableheading}
\makeatletter
\@ifpackageloaded{tcolorbox}{}{\usepackage[skins,breakable]{tcolorbox}}
\@ifpackageloaded{fontawesome5}{}{\usepackage{fontawesome5}}
\definecolor{quarto-callout-color}{HTML}{909090}
\definecolor{quarto-callout-note-color}{HTML}{0758E5}
\definecolor{quarto-callout-important-color}{HTML}{CC1914}
\definecolor{quarto-callout-warning-color}{HTML}{EB9113}
\definecolor{quarto-callout-tip-color}{HTML}{00A047}
\definecolor{quarto-callout-caution-color}{HTML}{FC5300}
\definecolor{quarto-callout-color-frame}{HTML}{acacac}
\definecolor{quarto-callout-note-color-frame}{HTML}{4582ec}
\definecolor{quarto-callout-important-color-frame}{HTML}{d9534f}
\definecolor{quarto-callout-warning-color-frame}{HTML}{f0ad4e}
\definecolor{quarto-callout-tip-color-frame}{HTML}{02b875}
\definecolor{quarto-callout-caution-color-frame}{HTML}{fd7e14}
\makeatother
\makeatletter
\makeatother
\makeatletter
\@ifpackageloaded{bookmark}{}{\usepackage{bookmark}}
\makeatother
\makeatletter
\@ifpackageloaded{caption}{}{\usepackage{caption}}
\AtBeginDocument{%
\ifdefined\contentsname
\renewcommand*\contentsname{Table of contents}
\else
\newcommand\contentsname{Table of contents}
\fi
\ifdefined\listfigurename
\renewcommand*\listfigurename{List of Figures}
\else
\newcommand\listfigurename{List of Figures}
\fi
\ifdefined\listtablename
\renewcommand*\listtablename{List of Tables}
\else
\newcommand\listtablename{List of Tables}
\fi
\ifdefined\figurename
\renewcommand*\figurename{Figure}
\else
\newcommand\figurename{Figure}
\fi
\ifdefined\tablename
\renewcommand*\tablename{Table}
\else
\newcommand\tablename{Table}
\fi
}
\@ifpackageloaded{float}{}{\usepackage{float}}
\floatstyle{ruled}
\@ifundefined{c@chapter}{\newfloat{codelisting}{h}{lop}}{\newfloat{codelisting}{h}{lop}[chapter]}
\floatname{codelisting}{Listing}
\newcommand*\listoflistings{\listof{codelisting}{List of Listings}}
\makeatother
\makeatletter
\@ifpackageloaded{caption}{}{\usepackage{caption}}
\@ifpackageloaded{subcaption}{}{\usepackage{subcaption}}
\makeatother
\makeatletter
\@ifpackageloaded{tcolorbox}{}{\usepackage[skins,breakable]{tcolorbox}}
\makeatother
\makeatletter
\@ifundefined{shadecolor}{\definecolor{shadecolor}{rgb}{.97, .97, .97}}
\makeatother
\makeatletter
\@ifundefined{codebgcolor}{\definecolor{codebgcolor}{named}{light}}
\makeatother
\makeatletter
\makeatother
\ifLuaTeX
\usepackage{selnolig} % disable illegal ligatures
\fi
\IfFileExists{bookmark.sty}{\usepackage{bookmark}}{\usepackage{hyperref}}
\IfFileExists{xurl.sty}{\usepackage{xurl}}{} % add URL line breaks if available
\urlstyle{same} % disable monospaced font for URLs
\hypersetup{
pdftitle={temp\_book},
pdfauthor={Norah Jones},
colorlinks=true,
linkcolor={highlight},
filecolor={Maroon},
citecolor={Blue},
urlcolor={highlight},
pdfcreator={LaTeX via pandoc}}
\title{temp\_book}
\author{Norah Jones}
\date{2024-04-01}
\begin{document}
\maketitle
\pagestyle{mystyle}
\ifdefined\Shaded\renewenvironment{Shaded}{\begin{tcolorbox}[colback={codebgcolor}, sharp corners, enhanced, breakable, frame hidden, borderline west={3pt}{0pt}{shadecolor}, boxrule=0pt]}{\end{tcolorbox}}\fi
\renewcommand*\contentsname{Table of contents}
{
\hypersetup{linkcolor=}
\setcounter{tocdepth}{2}
\tableofcontents
}
\bookmarksetup{startatroot}
\hypertarget{preface}{%
\chapter*{Preface}\label{preface}}
\addcontentsline{toc}{chapter}{Preface}
\markboth{Preface}{Preface}
This is a Quarto book.
To learn more about Quarto books visit
\url{https://quarto.org/docs/books}.
\begin{Shaded}
\begin{Highlighting}[]
\DecValTok{33333333333333333333333333333333333333333333333333333333333333333333333333333333}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
[1] 3.333333e+79
\end{verbatim}
\bookmarksetup{startatroot}
\hypertarget{intro-to-ggplot2}{%
\chapter{Intro to ggplot2}\label{intro-to-ggplot2}}
\hypertarget{introduction}{%
\section{Introduction}\label{introduction}}
Welcome to The GRAPH Courses' Data Visualization course!
We will focus on learning how to use the \textbf{\{ggplot2\} package} to
produce high quality visualizations in R.
\begin{figure}
{\centering \includegraphics[width=2in,height=\textheight]{images/ggplot2-part-of-tidyverse.png}
}
\caption{\{ggplot2\} is one of the core packages of the \{tidyverse\}
metapackage. It is the most popular R package for data visualization.}
\end{figure}
Let's dive in!
\hypertarget{learning-objectives}{%
\section{Learning objectives}\label{learning-objectives}}
By the end of this lesson you should be able to:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
Recall and explain how the \textbf{\{ggplot2\}} package for data
visualization is based on a theoretical framework called the
\textbf{grammar of graphics}.
\item
Name and describe the 3 essential components required for building a
graph: \textbf{data}, \textbf{aesthetics}, and \textbf{geometries}.
\item
Write code to \textbf{build a complete \texttt{ggplot}}
\textbf{graphic} by correctly supplying the 3 essential layers to the
\textbf{\texttt{ggplot()}} \textbf{function}.
\item
Create different types of plots such as \textbf{scatter plots},
\textbf{line graphs}, and \textbf{bar graphs}.
\item
Add or modify visual elements of a plot such as \textbf{color} and
\textbf{size}.
\item
Distinguish between between \textbf{aesthetic mappings} and
\textbf{fixed aesthetics}, and how to apply them.
\end{enumerate}
\begin{figure}
{\centering \includegraphics[width=6.25in,height=\textheight]{images/ggplot2_masterpiece.png}
}
\caption{Illustration by Allison Horst}
\end{figure}
\hypertarget{packages}{%
\section{Packages}\label{packages}}
The \{tidyverse\} meta package includes \{ggplot2\}, so we don't need to
add it separately. The \{here\} package will help us correctly reference
file paths.
\begin{Shaded}
\begin{Highlighting}[]
\DocumentationTok{\#\# Load packages }
\NormalTok{pacman}\SpecialCharTok{::}\FunctionTok{p\_load}\NormalTok{(tidyverse,}
\NormalTok{ here)}
\end{Highlighting}
\end{Shaded}
\hypertarget{measles-outbreaks-in-niger}{%
\section{Measles outbreaks in Niger}\label{measles-outbreaks-in-niger}}
In this lesson, we will explore patterns of measles outbreaks in Niger.
Measles is a \textbf{highly infectious virus} spread by airborne
respiratory droplets.
{[}Slide presentation about geography{]}
Since it is transmitted through direct contact, \textbf{population
density} is an important driver of measles dynamics.
\hypertarget{the-nigerm-dataset}{%
\subsection{\texorpdfstring{The \texttt{nigerm}
dataset}{The nigerm dataset}}\label{the-nigerm-dataset}}
We will be creating plots with a dataset of weekly reported measles
cases at the region level in Niger.
These data were collected by the Ministry of Health of Niger, from 1 Jan
1995 to 31 Dec 2005.
To get started, let's first load the (preprocessed) data set:
\begin{Shaded}
\begin{Highlighting}[]
\DocumentationTok{\#\# Import data frame to RStudio Environment}
\FunctionTok{load}\NormalTok{(}\FunctionTok{here}\NormalTok{(}\StringTok{"data/clean/nigerm\_cases\_rgn.RData"}\NormalTok{))}
\end{Highlighting}
\end{Shaded}
Take a moment to browse through the data:
\begin{Shaded}
\begin{Highlighting}[]
\DocumentationTok{\#\# Print Niger measles (nigerm) data frame}
\NormalTok{nigerm}
\end{Highlighting}
\end{Shaded}
\begin{figure}[H]
{\centering \includegraphics{data_on_display_ls01_gg_intro_files/figure-pdf/unnamed-chunk-5-1.pdf}
}
\end{figure}
The \textbf{\texttt{nigerm}} data frame has 4 variables (or columns):
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
\textbf{\texttt{year}}: Calendar year (ranges from 1995 to 2005)
\item
\textbf{\texttt{week}}: Week of the year (ranges from 1 to 52)
\item
\textbf{\texttt{region}}: Region in which the cases were recorded (see
figure below)
\item
\textbf{\texttt{cases}}: Number of measles cases reported
\end{enumerate}
\begin{figure}
{\centering \includegraphics{images/niger_administrative_divisions.png}
}
\caption{Administrative divisions of Niger: Districts and Regions}
\end{figure}
Several papers have investigated these trends, linking measles to human
activity, migration, and seasonality.
\begin{figure}
{\centering \includegraphics{images/paste-B863326A.png}
}
\caption{Research articles that have used this dataset, and analyzed it
in R!}
\end{figure}
These studies are much more complex than what we will do there, but
let's see if we can find any patterns even with basic
\textbf{exploratory data visualization}.
We can get some information about patterns in this data by inspecting
summary statistics given by the \textbf{\texttt{summary()}} function:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{summary}\NormalTok{(nigerm)}
\end{Highlighting}
\end{Shaded}
\begin{verbatim}
year week region cases
Min. :1995 Min. : 1.00 Agadez : 572 Min. : 0.0
1st Qu.:1997 1st Qu.:13.75 Diffa : 572 1st Qu.: 1.0
Median :2000 Median :26.50 Dosso : 572 Median : 16.0
Mean :2000 Mean :26.50 Maradi : 572 Mean : 100.3
3rd Qu.:2003 3rd Qu.:39.25 Niamey : 572 3rd Qu.: 86.0
Max. :2005 Max. :52.00 Tahoua : 572 Max. :1887.0
(Other):1144
\end{verbatim}
This gives us values for the maximum, minimum, and quartiles of each
numeric variable, and the number of observations (rows) for each region.
This is summary useful, but it omits a large amount information
contained in the dataset.
Keep in mind that summary statistics can be highly misleading, and a
simple plot can reveal a lot more.
The easiest and clearest way to analyze patterns from this dataset is to
visualize it!
The best way to do this in R is with \{ggplot2\}. So let's see how that
works.
\hypertarget{the-layered-grammar-of-graphics}{%
\subsection{The layered Grammar of
Graphics}\label{the-layered-grammar-of-graphics}}
The \texttt{gg} in \texttt{ggplot} is short for ``\texttt{g}rammar of
\texttt{g}raphics'', which is the data visualization philosophy that
\{ggplot2\} is based on.
The \textbf{grammar of graphics} is a theoretical framework which
deconstructs the process of producing a graph.
Think of how we construct and form sentences in written and spoken
languages by combining different elements, like nouns, verbs, articles,
subjects, objects, etc. We can't just combine these elements in any
arbitrary order; we must do so following a set of rules known as a
linguistic grammar.
Similarly, the grammar of graphics (GG) defines a set of rules for
constructing \emph{graphics} by combining different types of elements,
known as \emph{layers}.
\begin{figure}
{\centering \includegraphics[width=4.08333in,height=\textheight]{images/gglayers.png}
}
\caption{The grammar of graphics framework dissects a graph into
individual components, which belong to these seven distinct layers. We
take these different layers and combine them together to build a plot.}
\end{figure}
The three layers at the bottom of this figure - \textbf{data},
\textbf{aesthetics}, and \textbf{geometries} - are required for building
any plot.
Let's define what they mean:
\begin{enumerate}
\def\labelenumi{\arabic{enumi}.}
\item
\textbf{\texttt{data}}: the dataset containing the variables of
interest.
\includegraphics[width=4.6875in,height=\textheight]{images/gglayers_data.png}
\item
\textbf{\texttt{aes}}thetics: things we can see that visually
communicate information in our data.
\includegraphics[width=4.6875in,height=\textheight]{images/gglayers_aes.png}
\item
\textbf{\texttt{geom}}etry: the geometric shape used to represent data
in a plot: points, lines, bars, etc.
\includegraphics[width=4.6875in,height=\textheight]{images/gglayers_geom.png}
\end{enumerate}
You might be wondering why we wrote \texttt{data}, \texttt{geom}, and
\texttt{aes} in a computer code type font. You'll see very shortly that
we use these terms in R code to represent GG layers.
\begin{tcolorbox}[enhanced jigsaw, colframe=quarto-callout-note-color-frame, colbacktitle=quarto-callout-note-color!10!white, titlerule=0mm, opacitybacktitle=0.6, breakable, toprule=.15mm, arc=.35mm, rightrule=.15mm, colback=white, bottomrule=.15mm, opacityback=0, toptitle=1mm, left=2mm, bottomtitle=1mm, title=\textcolor{quarto-callout-note-color}{\faInfo}\hspace{0.5em}{Challenge}, leftrule=.75mm, coltitle=black]
The terms and syntax used for \texttt{ggplot} functions, arguments, and
layers can be hard to keep up with at first, but as you gain experience
using these terms to make plots in R, you will become fluent in no time.
\end{tcolorbox}
\hypertarget{working-through-the-essential-layers}{%
\section{Working through the essential
layers}\label{working-through-the-essential-layers}}
In this section, we will work towards a first plot with \{ggplot2\}. It
will be a scatter plot using data from \texttt{nigerm}.
For easier plotting in this lesson, we will use a smaller subsets of the
\texttt{nigerm} data frame at a time.
First let's create one called \texttt{nigerm96}, which only contains
measles case data for the year 1996. Running the code below will create
\texttt{nigerm96} and add it to your RStudio Environment:
\begin{Shaded}
\begin{Highlighting}[]
\DocumentationTok{\#\# Create nigerm96 data frame}
\NormalTok{nigerm96 }\OtherTok{\textless{}{-}}\NormalTok{ nigerm }\SpecialCharTok{\%\textgreater{}\%}
\FunctionTok{filter}\NormalTok{(year }\SpecialCharTok{==} \DecValTok{1996}\NormalTok{) }\SpecialCharTok{\%\textgreater{}\%} \CommentTok{\# filter to only include rows from 1996}
\FunctionTok{select}\NormalTok{(}\SpecialCharTok{{-}}\NormalTok{year) }\CommentTok{\# remove the year column}
\end{Highlighting}
\end{Shaded}
\begin{tcolorbox}[enhanced jigsaw, colframe=quarto-callout-note-color-frame, colbacktitle=quarto-callout-note-color!10!white, titlerule=0mm, opacitybacktitle=0.6, breakable, toprule=.15mm, arc=.35mm, rightrule=.15mm, colback=white, bottomrule=.15mm, opacityback=0, toptitle=1mm, left=2mm, bottomtitle=1mm, title=\textcolor{quarto-callout-note-color}{\faInfo}\hspace{0.5em}{Reminder}, leftrule=.75mm, coltitle=black]
The \texttt{select()} and \texttt{filter()} functions are part of the
\{dplyr\} package for data manipulation, which is a core package of the
\{tidyverse\}. These topics are covered in the Data Wrangling course.
See The GRAPH Courses \href{https://thegraphcourses.org/}{website} for
more.
\end{tcolorbox}
Let's look at our new dataframe, \texttt{nigerm96}:
\begin{Shaded}
\begin{Highlighting}[]
\DocumentationTok{\#\# Print nigerm96}
\NormalTok{nigerm96}
\end{Highlighting}
\end{Shaded}
\begin{figure}[H]
{\centering \includegraphics{data_on_display_ls01_gg_intro_files/figure-pdf/unnamed-chunk-8-1.pdf}
}
\end{figure}
\hypertarget{building-a-ggplot-in-steps}{%
\subsection{\texorpdfstring{Building a \texttt{ggplot()} in
steps}{Building a ggplot() in steps}}\label{building-a-ggplot-in-steps}}
Time to start building a \texttt{ggplot} in increments! We'll do this by
starting with a blank canvas and then adding one layer at a time.
\textbf{Step 0: Call the \texttt{ggplot()} function}
\begin{Shaded}
\begin{Highlighting}[]
\DocumentationTok{\#\# Call the \textasciigrave{}ggplot()\textasciigrave{} function}
\FunctionTok{ggplot}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
\begin{figure}[H]
{\centering \includegraphics{data_on_display_ls01_gg_intro_files/figure-pdf/unnamed-chunk-9-1.pdf}
}
\end{figure}
As you can see, this gives us nothing but a blank canvas. But not to
worry, we're about to add some more elements.
\textbf{Step 1: Provide data}
The first input we need to supply the \texttt{ggplot()} function is the
data layer (i.e., a data frame), by filling in the \texttt{data}
argument (\texttt{data\ =\ DF\_NAME}):
\begin{Shaded}
\begin{Highlighting}[]
\DocumentationTok{\#\# Data layer}
\FunctionTok{ggplot}\NormalTok{(}\AttributeTok{data =}\NormalTok{ nigerm96) }\CommentTok{\# what data to use}
\end{Highlighting}
\end{Shaded}
\begin{figure}[H]
{\centering \includegraphics{data_on_display_ls01_gg_intro_files/figure-pdf/unnamed-chunk-10-1.pdf}
}
\end{figure}
This gives us blank plot again, since we've only supplied one out of the
three inputs required for a complete graphic. Next we need to assign
variables to aesthetic mappings.
\textbf{Step 2: Define the variables}
What should we plot on our axes? Let's say we want to make an epidemic
time series plot. To do that, we plot time (in weeks) on the x-axis, and
disease incidence (number of reported cases) on the y-axis. In
\texttt{ggplot}-speak, we are \texttt{mapping} the variable
\texttt{cases} to the \texttt{x} aesthetic, and \texttt{week} to the
\texttt{y} aesthetic.
Let's tell \texttt{ggplot()} which variables to to plot on the
aesthetics layer with a \texttt{mapping} argument, using this syntax:
\texttt{mapping\ =\ aes(x\ =\ VAR1,\ y\ =\ VAR2)}.
\begin{Shaded}
\begin{Highlighting}[]
\DocumentationTok{\#\# Aesthetics layer: x and y position}
\FunctionTok{ggplot}\NormalTok{(}\AttributeTok{data =}\NormalTok{ nigerm96, }\CommentTok{\# what data to use}
\AttributeTok{mapping =} \FunctionTok{aes}\NormalTok{( }\CommentTok{\# supply a mapping in the form of an \textquotesingle{}aesthetic\textquotesingle{}}
\AttributeTok{x =}\NormalTok{ week, }\CommentTok{\# which variable to map onto the x{-}axis}
\AttributeTok{y =}\NormalTok{ cases)) }\CommentTok{\# which variable to map onto the y{-}axis}
\end{Highlighting}
\end{Shaded}
\begin{figure}[H]
{\centering \includegraphics{data_on_display_ls01_gg_intro_files/figure-pdf/unnamed-chunk-11-1.pdf}
}
\end{figure}
There's still no data plotted, but the axis scales, titles, and labels
are present. The x-axis marks weeks of the year from 1 to 52, and the
y-axis shows that the number of weekly reported cases per region ranges
from 0 to around 2000.
The plot is still lacking the required geometry layer.
\begin{tcolorbox}[enhanced jigsaw, colframe=quarto-callout-note-color-frame, colbacktitle=quarto-callout-note-color!10!white, titlerule=0mm, opacitybacktitle=0.6, breakable, toprule=.15mm, arc=.35mm, rightrule=.15mm, colback=white, bottomrule=.15mm, opacityback=0, toptitle=1mm, left=2mm, bottomtitle=1mm, title=\textcolor{quarto-callout-note-color}{\faInfo}\hspace{0.5em}{Key Point}, leftrule=.75mm, coltitle=black]
\texttt{aes()} stands for aesthetics - things we can see. Variables are
always inside the \texttt{aes()} function, which in return is inside a
\texttt{ggplot()}. Take a moment to observe the double closing brackets
\textbf{\texttt{))}} - the first one belongs to \texttt{aes()}, the
second one to \texttt{ggplot()}.
\end{tcolorbox}
\textbf{Step 3: Specify which type of plot to create}
Finally, we add a geometry layer using a \texttt{geom\_*} function. This
determines which geometric objects - or visual markers - should be used
to map the data.
Since we are looking at the relationship of two numerical variables, it
makes sense to use a \textbf{scatter plot}. The geometric objects used
to represent data on scatter plots are \textbf{points}, and the
\texttt{geom\_*} function for scatter plots is conveniently named
\textbf{\texttt{geom\_point()}}. We'll add this function as new layer
using a \textbf{\texttt{+}} sign:
\begin{Shaded}
\begin{Highlighting}[]
\DocumentationTok{\#\# Geometries layer: points}
\FunctionTok{ggplot}\NormalTok{(}\AttributeTok{data =}\NormalTok{ nigerm96, }\CommentTok{\# what data to use}
\AttributeTok{mapping =} \FunctionTok{aes}\NormalTok{( }\CommentTok{\# define mapping}
\AttributeTok{x =}\NormalTok{ week, }\CommentTok{\# which variable to map onto the x{-}axis}
\AttributeTok{y =}\NormalTok{ cases)) }\SpecialCharTok{+} \CommentTok{\# which variable to map onto the y{-}axis}
\FunctionTok{geom\_point}\NormalTok{() }\CommentTok{\# add a geom of type \textasciigrave{}point\textasciigrave{} (for scatter plot)}
\end{Highlighting}
\end{Shaded}
\begin{figure}[H]
{\centering \includegraphics{data_on_display_ls01_gg_intro_files/figure-pdf/unnamed-chunk-12-1.pdf}
}
\end{figure}
Points have been added, and this is now a complete scatter plot! There
are 8 points per week, representing each of the 8 regions (but at this
point we cannot tell which point is from which region).
\begin{tcolorbox}[enhanced jigsaw, colframe=quarto-callout-note-color-frame, colbacktitle=quarto-callout-note-color!10!white, titlerule=0mm, opacitybacktitle=0.6, breakable, toprule=.15mm, arc=.35mm, rightrule=.15mm, colback=white, bottomrule=.15mm, opacityback=0, toptitle=1mm, left=2mm, bottomtitle=1mm, title=\textcolor{quarto-callout-note-color}{\faInfo}\hspace{0.5em}{Reminder}, leftrule=.75mm, coltitle=black]
The \texttt{aes}thetic function is nested inside the \texttt{ggplot()}
function, so be sure to close the brackets for both functions before
adding the \texttt{+} sign for the \texttt{geom\_*} function, or your
code will not run correctly.
\end{tcolorbox}
It's your turn to practice plotting with \texttt{ggplot()}! For practice
exercises in this lesson, you will be using a different subset of
\texttt{nigerm} called \textbf{\texttt{nigerm04}}, which contains only
data from the year 2004:
\includegraphics{data_on_display_ls01_gg_intro_files/figure-pdf/unnamed-chunk-13-1.pdf}
Plotting with a different set of data will also allow you to explore if
the patterns we see for 1996 is also true for 2004.
\begin{tcolorbox}[enhanced jigsaw, colframe=quarto-callout-tip-color-frame, colbacktitle=quarto-callout-tip-color!10!white, titlerule=0mm, opacitybacktitle=0.6, breakable, toprule=.15mm, arc=.35mm, rightrule=.15mm, colback=white, bottomrule=.15mm, opacityback=0, toptitle=1mm, left=2mm, bottomtitle=1mm, title=\textcolor{quarto-callout-tip-color}{\faLightbulb}\hspace{0.5em}{Practice}, leftrule=.75mm, coltitle=black]
Using the \texttt{nigerm04} data frame, write \texttt{ggplot} code that
will create a scatter plot displaying the relationship between
\texttt{cases} on the y-axis and \texttt{week} on the x-axis.
\end{tcolorbox}
\hypertarget{modifying-the-layers}{%
\section{Modifying the layers}\label{modifying-the-layers}}
Generally speaking, the grammar of graphics allows for a high degree of
customization of plots and also a consistent framework for easily
updating and modifying them.
We can tinker with our existing code to switch up the data, aesthetics,
and geometry inputs supplied to \texttt{ggplot()}, and create variations
of the original plot. In fact, you've already done this by changing the
dataset from \texttt{nigerm96} to \texttt{nigerm04} in the practice
question.
Similarly, the \texttt{aes}thetics and \texttt{geom}etry inputs can also
be changed to create different visualizations. In the next few sections
we will take the scatter plot we built in the previous section, and make
incremental changes to modify different elements of the original code.
\hypertarget{changing-aesthetic-mappings}{%
\subsection{\texorpdfstring{Changing \texttt{aes}thetic
mappings}{Changing aesthetic mappings}}\label{changing-aesthetic-mappings}}
We created a scatter plot of \texttt{cases} vs \texttt{week} for
\texttt{nigerm96} with this code:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{ggplot}\NormalTok{(}\AttributeTok{data =}\NormalTok{ nigerm96, }
\AttributeTok{mapping =} \FunctionTok{aes}\NormalTok{(}\AttributeTok{x =}\NormalTok{ week, }
\AttributeTok{y =}\NormalTok{ cases)) }\SpecialCharTok{+}
\FunctionTok{geom\_point}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
\begin{figure}[H]
{\centering \includegraphics{data_on_display_ls01_gg_intro_files/figure-pdf/unnamed-chunk-19-1.pdf}
}
\end{figure}
If we copy the same code and change just one thing - by replacing the
\texttt{x} variable \texttt{week} (numerical) with \texttt{region}
(categorical) - we get what's called a \textbf{strip plot}:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{ggplot}\NormalTok{(}\AttributeTok{data =}\NormalTok{ nigerm96, }
\AttributeTok{mapping =} \FunctionTok{aes}\NormalTok{(}\AttributeTok{x =}\NormalTok{ region, }\CommentTok{\# change which variable to map on the x{-}axis }
\AttributeTok{y =}\NormalTok{ cases)) }\SpecialCharTok{+}
\FunctionTok{geom\_point}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
\begin{figure}[H]
{\centering \includegraphics{data_on_display_ls01_gg_intro_files/figure-pdf/unnamed-chunk-20-1.pdf}
}
\end{figure}
While the y-axis values of the points are the same as before, their
x-axis mappings have changed significantly. They are now mapped to 8
separate positions along the x-axis, each corresponding to a discrete
category of the \texttt{region} variable.
\hypertarget{changing-geom_-functions}{%
\subsection{\texorpdfstring{Changing \texttt{geom\_*}
functions}{Changing geom\_* functions}}\label{changing-geom_-functions}}
Similarly, we can modify the geometry layer to create a different type
of plot, while still using the same aesthetic mappings.
\begin{figure}
{\centering \includegraphics{images/geoms.png}
}
\caption{\{ggplot2\} has a variety of different \texttt{geom\_*}
functions and geometric objects which you can use to visualize your
data. Here are some examples of different types of geoms that can be
used with \texttt{ggplot()}.}
\end{figure}
Let's copy and paste the original scatter plot code once again, but this
time we will replace the \texttt{geom\_*} function instead of the
\texttt{x} aesthetic. If we change \texttt{geom\_point()} to
\textbf{\texttt{geom\_col()}}, we get a \textbf{bar plot} (sometimes
called a \texttt{col}umn chart):
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{ggplot}\NormalTok{(}\AttributeTok{data =}\NormalTok{ nigerm96, }
\AttributeTok{mapping =} \FunctionTok{aes}\NormalTok{(}\AttributeTok{x =}\NormalTok{ week,}
\AttributeTok{y =}\NormalTok{ cases)) }\SpecialCharTok{+}
\FunctionTok{geom\_col}\NormalTok{() }\CommentTok{\# declare that we want a bar plot}
\end{Highlighting}
\end{Shaded}
\begin{figure}[H]
{\centering \includegraphics{data_on_display_ls01_gg_intro_files/figure-pdf/unnamed-chunk-21-1.pdf}
}
\end{figure}
Again, the rest of the code is still the same - we just changed the key
word of the \texttt{geom\_*} function. However, the plot is
significantly different that either the scatter plot or the strip plot.
Notice that the y-axis has been rescaled. The height of each bar
represents the cumulative number of weekly cases, i.e, the total number
of cases reported from all eight regions that week, rather than showing
8 separate data points for each region.
\begin{tcolorbox}[enhanced jigsaw, colframe=quarto-callout-caution-color-frame, colbacktitle=quarto-callout-caution-color!10!white, titlerule=0mm, opacitybacktitle=0.6, breakable, toprule=.15mm, arc=.35mm, rightrule=.15mm, colback=white, bottomrule=.15mm, opacityback=0, toptitle=1mm, left=2mm, bottomtitle=1mm, title=\textcolor{quarto-callout-caution-color}{\faFire}\hspace{0.5em}{Error}, leftrule=.75mm, coltitle=black]
Not all plot types are interchangeable. Using a \texttt{geom\_*}
function that is not compatible with the variables you defined in
\texttt{aes()} will give you an error. For example, let's replace
\texttt{geom\_point()} with \texttt{geom\_histogram()} instead:
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{ggplot}\NormalTok{(}\AttributeTok{data =}\NormalTok{ nigerm96, }
\AttributeTok{mapping =} \FunctionTok{aes}\NormalTok{(}\AttributeTok{x =}\NormalTok{ week, }
\AttributeTok{y =}\NormalTok{ cases)) }\SpecialCharTok{+}
\FunctionTok{geom\_histogram}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
This is because a histogram shows the distribution of one numerical
variable. \texttt{ggplot()} can't map two variables to both the
\texttt{x} and \texttt{y}-axis positions with a histogram, so it throws
an error.
\end{tcolorbox}
\begin{tcolorbox}[enhanced jigsaw, colframe=quarto-callout-tip-color-frame, colbacktitle=quarto-callout-tip-color!10!white, titlerule=0mm, opacitybacktitle=0.6, breakable, toprule=.15mm, arc=.35mm, rightrule=.15mm, colback=white, bottomrule=.15mm, opacityback=0, toptitle=1mm, left=2mm, bottomtitle=1mm, title=\textcolor{quarto-callout-tip-color}{\faLightbulb}\hspace{0.5em}{Practice}, leftrule=.75mm, coltitle=black]
Use the \texttt{nigerm04} data frame to create a bar plot of weekly
cases with the \texttt{geom\_col()} function. Map \texttt{cases} on the
y-axis and \texttt{week} on the x-axis.
\end{tcolorbox}
\hypertarget{additional-aesthetic-mappings-inside-aes}{%
\subsection{\texorpdfstring{Additional aesthetic mappings inside
\texttt{aes()}}{Additional aesthetic mappings inside aes()}}\label{additional-aesthetic-mappings-inside-aes}}
So far, we have only mapped variables to the \texttt{x} and \texttt{y}
aesthetic attributes. We can also map variables to other aesthetics like
color, size, or shape.
\begin{figure}
{\centering \includegraphics{images/common_aesthetics_1.png}
}
\caption{Common aesthetic attributes used in \texttt{ggplot} graphics.}
\end{figure}
Let's return to our original scatter plot (\texttt{cases} vs
\texttt{week}):
\begin{Shaded}
\begin{Highlighting}[]
\FunctionTok{ggplot}\NormalTok{(}\AttributeTok{data =}\NormalTok{ nigerm96, }
\AttributeTok{mapping =} \FunctionTok{aes}\NormalTok{(}\AttributeTok{x =}\NormalTok{ week, }
\AttributeTok{y =}\NormalTok{ cases)) }\SpecialCharTok{+}
\FunctionTok{geom\_point}\NormalTok{()}
\end{Highlighting}
\end{Shaded}
\begin{figure}[H]