-
Notifications
You must be signed in to change notification settings - Fork 3
/
week5-ggplot2.html
911 lines (805 loc) · 38 KB
/
week5-ggplot2.html
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
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="generator" content="pandoc" />
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
<title>Week 5: Intro to ggplot</title>
<script src="site_libs/header-attrs-2.11/header-attrs.js"></script>
<script src="site_libs/jquery-3.6.0/jquery-3.6.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="site_libs/bootstrap-3.3.5/css/readable.min.css" rel="stylesheet" />
<script src="site_libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="site_libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<style>h1 {font-size: 34px;}
h1.title {font-size: 38px;}
h2 {font-size: 30px;}
h3 {font-size: 24px;}
h4 {font-size: 18px;}
h5 {font-size: 16px;}
h6 {font-size: 12px;}
code {color: inherit; background-color: rgba(0, 0, 0, 0.04);}
pre:not([class]) { background-color: white }</style>
<script src="site_libs/jqueryui-1.11.4/jquery-ui.min.js"></script>
<link href="site_libs/tocify-1.9.1/jquery.tocify.css" rel="stylesheet" />
<script src="site_libs/tocify-1.9.1/jquery.tocify.js"></script>
<script src="site_libs/navigation-1.1/tabsets.js"></script>
<link href="site_libs/highlightjs-9.12.0/textmate.css" rel="stylesheet" />
<script src="site_libs/highlightjs-9.12.0/highlight.js"></script>
<link href="site_libs/font-awesome-5.1.0/css/all.css" rel="stylesheet" />
<link href="site_libs/font-awesome-5.1.0/css/v4-shims.css" rel="stylesheet" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<style type="text/css">
code{white-space: pre-wrap;}
span.smallcaps{font-variant: small-caps;}
span.underline{text-decoration: underline;}
div.column{display: inline-block; vertical-align: top; width: 50%;}
div.hanging-indent{margin-left: 1.5em; text-indent: -1.5em;}
ul.task-list{list-style: none;}
</style>
<style type="text/css">code{white-space: pre;}</style>
<script type="text/javascript">
if (window.hljs) {
hljs.configure({languages: []});
hljs.initHighlightingOnLoad();
if (document.readyState && document.readyState === "complete") {
window.setTimeout(function() { hljs.initHighlighting(); }, 0);
}
}
</script>
<link rel="stylesheet" href="styles.css" type="text/css" />
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
img {
max-width:100%;
}
.tabbed-pane {
padding-top: 12px;
}
.html-widget {
margin-bottom: 20px;
}
button.code-folding-btn:focus {
outline: none;
}
summary {
display: list-item;
}
pre code {
padding: 0;
}
</style>
<style type="text/css">
.dropdown-submenu {
position: relative;
}
.dropdown-submenu>.dropdown-menu {
top: 0;
left: 100%;
margin-top: -6px;
margin-left: -1px;
border-radius: 0 6px 6px 6px;
}
.dropdown-submenu:hover>.dropdown-menu {
display: block;
}
.dropdown-submenu>a:after {
display: block;
content: " ";
float: right;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
border-width: 5px 0 5px 5px;
border-left-color: #cccccc;
margin-top: 5px;
margin-right: -10px;
}
.dropdown-submenu:hover>a:after {
border-left-color: #adb5bd;
}
.dropdown-submenu.pull-left {
float: none;
}
.dropdown-submenu.pull-left>.dropdown-menu {
left: -100%;
margin-left: 10px;
border-radius: 6px 0 6px 6px;
}
</style>
<script type="text/javascript">
// manage active state of menu based on current page
$(document).ready(function () {
// active menu anchor
href = window.location.pathname
href = href.substr(href.lastIndexOf('/') + 1)
if (href === "")
href = "index.html";
var menuAnchor = $('a[href="' + href + '"]');
// mark it active
menuAnchor.tab('show');
// if it's got a parent navbar menu mark it active as well
menuAnchor.closest('li.dropdown').addClass('active');
// Navbar adjustments
var navHeight = $(".navbar").first().height() + 15;
var style = document.createElement('style');
var pt = "padding-top: " + navHeight + "px; ";
var mt = "margin-top: -" + navHeight + "px; ";
var css = "";
// offset scroll position for anchor links (for fixed navbar)
for (var i = 1; i <= 6; i++) {
css += ".section h" + i + "{ " + pt + mt + "}\n";
}
style.innerHTML = "body {" + pt + "padding-bottom: 40px; }\n" + css;
document.head.appendChild(style);
});
</script>
<!-- tabsets -->
<style type="text/css">
.tabset-dropdown > .nav-tabs {
display: inline-table;
max-height: 500px;
min-height: 44px;
overflow-y: auto;
border: 1px solid #ddd;
border-radius: 4px;
}
.tabset-dropdown > .nav-tabs > li.active:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li.active:before {
content: "";
border: none;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open:before {
content: "";
font-family: 'Glyphicons Halflings';
display: inline-block;
padding: 10px;
border-right: 1px solid #ddd;
}
.tabset-dropdown > .nav-tabs > li.active {
display: block;
}
.tabset-dropdown > .nav-tabs > li > a,
.tabset-dropdown > .nav-tabs > li > a:focus,
.tabset-dropdown > .nav-tabs > li > a:hover {
border: none;
display: inline-block;
border-radius: 4px;
background-color: transparent;
}
.tabset-dropdown > .nav-tabs.nav-tabs-open > li {
display: block;
float: none;
}
.tabset-dropdown > .nav-tabs > li {
display: none;
}
</style>
<!-- code folding -->
<style type="text/css">
#TOC {
margin: 25px 0px 20px 0px;
}
@media (max-width: 768px) {
#TOC {
position: relative;
width: 100%;
}
}
@media print {
.toc-content {
/* see https://github.com/w3c/csswg-drafts/issues/4434 */
float: right;
}
}
.toc-content {
padding-left: 30px;
padding-right: 40px;
}
div.main-container {
max-width: 1200px;
}
div.tocify {
width: 20%;
max-width: 260px;
max-height: 85%;
}
@media (min-width: 768px) and (max-width: 991px) {
div.tocify {
width: 25%;
}
}
@media (max-width: 767px) {
div.tocify {
width: 100%;
max-width: none;
}
}
.tocify ul, .tocify li {
line-height: 20px;
}
.tocify-subheader .tocify-item {
font-size: 0.90em;
}
.tocify .list-group-item {
border-radius: 0px;
}
.tocify-subheader {
display: inline;
}
.tocify-subheader .tocify-item {
font-size: 0.95em;
}
</style>
</head>
<body>
<div class="container-fluid main-container">
<!-- setup 3col/9col grid for toc_float and main content -->
<div class="row">
<div class="col-xs-12 col-sm-4 col-md-3">
<div id="TOC" class="tocify">
</div>
</div>
<div class="toc-content col-xs-12 col-sm-8 col-md-9">
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="index.html">RWorkflow</a>
</div>
<div id="navbar" class="navbar-collapse collapse">
<ul class="nav navbar-nav">
<li>
<a href="set-up.html">
<span class="fa fa-clone"></span>
Set-up
</a>
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">
<span class="fa fa-calendar"></span>
Workshop Weekly Notes
<span class="caret"></span>
</a>
<ul class="dropdown-menu" role="menu">
<li>
<a href="week1.html">
<span class="fa fa-cogs"></span>
Week 1 RStudio + Version Control
</a>
</li>
<li>
<a href="week2.html">
<span class="fab fa-github-alt"></span>
Week 2 More Git/GitHub
</a>
</li>
<li>
<a href="week3.html">
<span class="fab fa-github"></span>
Week 3 GitHub
</a>
</li>
<li>
<a href="week4.html">
<span class="fa fa-file-code"></span>
Week 4 R Markdown
</a>
</li>
<li>
<a href="week5.html">
<span class="fa fa-chart-line"></span>
Week 5 ggplot2
</a>
</li>
<li>
<a href="week6.html">
<span class="fa fa-box"></span>
Week 6 packages
</a>
</li>
<li>
<a href="week7.html">
<span class="fa fa-circle"></span>
Week 7 roxygen and pkgdown
</a>
</li>
<li>
<a href="week8.html">
<span class="fa fa-box"></span>
Week 8 more packages
</a>
</li>
</ul>
</li>
<li>
<a href="https://rverse-tutorials.github.io/RWorkflow/">
<span class="fa fa-folder"></span>
Archive
</a>
</li>
<li>
<a href="https://rverse-tutorials.github.io/RWorkflow-NWFSC-2020">
<span class="fa fa-clock"></span>
2020 website
</a>
</li>
<li>
<a href="noaa.html">
<span class="fa fa-fish"></span>
NOAA
</a>
</li>
<li>
<a href="links.html">
<span class="fa fa-info"></span>
More resources
</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a href="https://github.com/RVerse-Tutorials/RWorkflow-NWFSC-2021">
<span class="fab fa-github"></span>
Repo
</a>
</li>
<li>
<a href="https://github.com/orgs/RWorkflow-Workshop-2021">Org</a>
</li>
</ul>
</div><!--/.nav-collapse -->
</div><!--/.container -->
</div><!--/.navbar -->
<div id="header">
<h1 class="title toc-ignore">Week 5: Intro to ggplot</h1>
</div>
<p>This week I will give an introduction to plotting with the <strong>ggplot2</strong> package. Getting a basic familiarity with <strong>ggplot2</strong> will really save you a lot of time that you spend futzing with plots.</p>
<p>This is oriented to those with little or no experience using <strong>ggplot2</strong> or those who have tried it and gotten frustrated. If you already use <strong>ggplot2</strong>, you won’t find this session very interesting. The goal of this session is to get you started. Once you have the basics, there are a gazillion ggplot tutorials online (though personally the basics are all I need).</p>
<p>You can <a href="https://github.com/RWorkflow-Workshop-2021/Week5">clone my Week 5 repository</a> or open the <a href="https://rstudio.cloud/project/2668698">respository in R Studio Cloud</a> and work from there. Once in either place, open <code>week5-ggplot2.Rmd</code> and click the Knit button.</p>
<p>If you are working on your own computer, you will need to install the <strong>ggplot2</strong> and <strong>gridExtra</strong> packages.</p>
<pre class="r"><code>library(ggplot2)
library(gridExtra)</code></pre>
<div id="basic-xy-plot" class="section level1">
<h1>Basic xy plot</h1>
<div id="workflow" class="section level2">
<h2>Workflow</h2>
<p>Let’s say you wanted to make a simple xy plot with <code>plot()</code>. Here’s your workflow.</p>
<ul>
<li>Decide on <code>x</code> or use the default (1 to the number of data points).</li>
<li>Decide on <code>y</code>.</li>
<li>Plot with <code>plot(x,y)</code></li>
</ul>
<pre class="r"><code>val <- mtcars$mpg
x <- mtcars$hp
plot(x, val, type="p")</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-2-1.png" width="672" /></p>
<p>Here’s your <code>ggplot()</code> workflow.</p>
<ul>
<li>Decide on <code>x</code> or use the default (1 to the number of data points).</li>
<li>Decide on <code>y</code>.</li>
<li>Make a data frame with <code>x</code> and <code>y</code>.</li>
<li>Create the plot object with a call to <code>ggplot()</code> to tell it the data frame and then what the <code>x</code> and <code>y</code> to use. The latter is with <code>aes()</code> (aesthestics).</li>
<li>Add points or lines to the plot with <code>geom_line()</code> or <code>geom_point()</code>.</li>
</ul>
<pre class="r"><code>df <- data.frame(x=mtcars$hp, val=mtcars$mpg)
p1 <- ggplot(df, aes(x=x, y=val)) #set up data and x and y
p2 <- p1 + geom_point() # Tell it what to do with that (add a line)
p2 # plot it</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-3-1.png" width="672" /></p>
<p>Typically you’d just write the call like so</p>
<pre><code>ggplot(df, aes(x=x, y=val)) + geom_point()</code></pre>
<p>But I assigned the calls to objects <code>p1</code> and <code>p2</code> so you can see that both are ggplot objects.</p>
<pre class="r"><code>class(p1)</code></pre>
<pre><code>## [1] "gg" "ggplot"</code></pre>
<pre class="r"><code>class(p2)</code></pre>
<pre><code>## [1] "gg" "ggplot"</code></pre>
<p>That feature is going to be super helpful because it means you can easily add elements to a ggplot without worrying about <code>y</code> axis limits or figure sizing.</p>
<pre class="r"><code>p2 + geom_line()</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-5-1.png" width="672" /></p>
</div>
</div>
<div id="modifying-your-plot" class="section level1">
<h1>Modifying your plot</h1>
<div id="points-and-lines" class="section level2">
<h2>Points and lines</h2>
<p>With <code>plot()</code>, you alter the points and lines with arguments passed to <code>plot()</code>.</p>
<ul>
<li><code>pch</code> (point type), <code>lty</code> (linetype), <code>type</code> (“l”, “b”, “p”), <code>lwd</code> (line width), <code>cex</code> (point size)</li>
</ul>
<pre class="r"><code>plot(x, val, type="b", lwd=2, lty=2,
pch=21, col="red", cex=4, bg="blue")</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-6-1.png" width="672" /></p>
<p>With <code>ggplot()</code>, the approach is quite different and the names are mostly totally different. A cheatsheet of things you commonly use will be helpful when start (I still use one).</p>
<p>There are two different workflows that you need to decide on.</p>
<ol style="list-style-type: decimal">
<li><em>Dynamic colors etc</em>: Let <code>ggplot()</code> pick your colors, points, line widths etc.</li>
<li><em>Fixed colors etc</em>: Manually choose your colors, points, line widths etc, aka use a fixed value.</li>
</ol>
<p>Gravitating to option 1 will make your life with <code>ggplot()</code> easier, but let’s start with option 2.</p>
<p><img src="images/Emblem-important-red.svg.png" alt="Important" /> <em>Fixed</em> lines, points attributes go <em>outside</em> of <code>aes()</code> in a <code>geom_...()</code> call. <em>Dynamic</em> attributes go <em>inside</em> of <code>aes()</code>.</p>
<p>Look at <code>?geom_point</code> to see the attributes that you can pass in.</p>
<pre class="r"><code>ggplot(df, aes(x=x, y=val)) + geom_point(col="blue")</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-7-1.png" width="672" /></p>
<p>The length of the fixed attribute must be 1 or the length of the data.</p>
<pre class="r"><code>ggplot(df, aes(x=x, y=val)) +
geom_point(shape=21, col="blue", fill=mtcars$carb, size=6, alpha=.5, stroke=2)</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-8-1.png" width="672" /></p>
<p>Ways to set attributes that won’t work as you think:</p>
<p>Putting color outside of <code>aes()</code> in <code>ggplot()</code> does nothing. <code>ggplot()</code> sets up the data to use, but information outside <code>aes()</code> doesn’t flow to the plotting functions like <code>geom_point()</code>.</p>
<pre class="r"><code>ggplot(df, aes(x=x, y=val), col="blue") + geom_point()</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-9-1.png" width="672" /></p>
<p>Putting color inside of <code>aes()</code> in <code>ggplot()</code> has a non-intuitive effect. Plot attributes, like color, in <code>aes()</code> are converted to factors and the colors (etc) will be choosen dynamically. The name “blue” is not a color is the a factor and <code>ggplot()</code> gives the first factor the color red in this case. Information in <code>aes()</code> will <em>flow</em> to the rest of the plot unless you tell the <code>geom_point()</code> otherwise).</p>
<pre class="r"><code>ggplot(df, aes(x=x, y=val, color="blue")) + geom_point()</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-10-1.png" width="672" /></p>
<p>How do we <em>tell</em> <code>geom_point()</code> not to use the color value in <code>aes()</code> in <code>ggplot()</code>? Tell it to use a fixed value by putting <code>col="blue"</code> outside of an <code>aes()</code> call in <code>geom_point()</code>.</p>
<pre class="r"><code>ggplot(df, aes(x=x, y=val)) + geom_point(col="blue")</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-11-1.png" width="672" /></p>
<p>What happens if we put the color in <code>aes()</code> in <code>geom_point()</code>?</p>
<pre class="r"><code>ggplot(df, aes(x=x, y=val)) + geom_point(aes(color="blue"))</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-12-1.png" width="672" /></p>
<p>Let’s make a plot with big red points and a thick blue line.</p>
<pre class="r"><code>p1 <- ggplot(df, aes(x=x, y=val)) +
geom_line(col="blue", size=2) +
geom_point(col="red", size=3)
p1</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-13-1.png" width="672" /></p>
<p>Let’s add a column plot to that. I pass in <code>alpha</code> to add some transparency to the columns so they don’t wipe out the line.</p>
<pre class="r"><code>p1 + geom_col(alpha=0.5, position="dodge")</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-14-1.png" width="672" /></p>
</div>
<div id="labels-and-limits" class="section level2">
<h2>Labels and limits</h2>
<p>With <code>plot()</code>, you alter the labels and limits with arguments passed to <code>plot()</code>.</p>
<ul>
<li><code>xlab</code> and <code>ylab</code> (labels), <code>mail</code> (title), <code>ylim</code> and <code>xlim</code> (limits)</li>
</ul>
<pre class="r"><code>plot(x, val, type="p", xlab="time", ylab="value",
xlim=c(100,200), ylim=c(0,40), main="plot plot")</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-15-1.png" width="672" /></p>
<p>With <code>ggplot</code>, it’s pretty similar but you use functions. Ignore the NA warning. I’ll show how to stop that later. ggplot likes to gives warnings about things that it knows how to deal with.</p>
<pre class="r"><code>ggplot(df, aes(x=x, y=val)) +
geom_point() +
xlab("time") + ylab("value") +
ggtitle("ggplot plot") +
xlim(c(100,200)) + ylim(c(0,40))</code></pre>
<pre><code>## Warning: Removed 16 rows containing missing values (geom_point).</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-16-1.png" width="672" /></p>
</div>
</div>
<div id="changing-the-whole-look" class="section level1">
<h1>Changing the whole look</h1>
<p>ggplot uses themes to set the look of your plot and you can change the whole look by setting a different theme. You can also just tweak one element of the plot’s existing theme. Note because we fixed the line and point colors, we override some theme elements (eg, line colors). See <code>?theme_bw</code> to see all the themes. See <code>?theme</code> to learn how to change one element of your plot design.</p>
<pre class="r"><code>p1 + theme_classic()</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-17-1.png" width="672" /></p>
</div>
<div id="adding-lines-or-points" class="section level1">
<h1>Adding lines or points</h1>
<p>Let’s say you want to plot 2 lines.</p>
<div id="workflow-1" class="section level2">
<h2>Workflow</h2>
<p>In <code>plot()</code> your workflow is</p>
<ul>
<li>Define <code>x1</code> and <code>x2</code> (if different)</li>
<li>Define <code>y1</code> and <code>y2</code></li>
<li>Plot <code>y1</code> <em>with limits adjusted for the data we are adding</em>.</li>
<li>Add <code>y2</code> to the plot.</li>
</ul>
<pre class="r"><code>val2 <- val+10
plot(x, val, ylim=c(0,50))
lines(x[order(x)], val2[order(x)])</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-18-1.png" width="672" /></p>
<p>In <code>ggplot()</code> you have two possible workflows. First one could be like the <code>plot()</code> workflow. This will cause you problems if you later want to arrange these data into separate plots, but lets go ahead and do this. Sometimes this is the easiest way to get done what you need to do.</p>
<ul>
<li>Define <code>x1</code> and <code>x2</code> (if different)</li>
<li>Define <code>y1</code> and <code>y2</code></li>
<li>Make data frames <code>df</code> and <code>df2</code> for both.</li>
<li>Set up the plot with <code>ggplot()</code> and <code>df</code></li>
<li>Add points with <code>geom_point()</code></li>
<li>Add <code>df2</code> using <code>geom_line()</code> with <code>df2</code> passed in and <code>aes()</code> call.</li>
</ul>
<p>How <code>aes()</code> is working. <code>aes()</code> information is flowing rightward. Everything to the right will inherit the data frame and <code>aes()</code> info in <code>ggplot()</code> unless you specifiy new data or new <code>aes()</code> (or use <code>inherit.aes=FALSE</code>).</p>
<pre class="r"><code>df2 <- data.frame(x=x, val2=val+10)
ggplot(data=df, aes(x=x, y=val)) +
geom_point() +
geom_line(data=df2, aes(x=x, y=val2))</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-19-1.png" width="672" /></p>
<p>This inheriting feature is usually very handy, but when working with multiple data frames, it is often clearer if you keep the data and <code>aes()</code> with the points and lines. Note since there is no data or <code>aes()</code> specified in <code>ggplot()</code> , there is no inheriting of data.</p>
<pre class="r"><code>ggplot() +
geom_point(data=df, aes(x=x, y=val)) +
geom_line(data=df2, aes(x=x, y=val2))</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-20-1.png" width="672" /></p>
<p>The lack of data and aesthetics in <code>ggplot()</code> means that this code will throw an error. <code>geom_line()</code> has data but no aesthetics because it can’t inherit that from <code>ggplot()</code>.</p>
<pre class="r"><code>ggplot() +
geom_point(data=df, aes(x=x, y=val)) +
geom_line(data=df2)</code></pre>
<pre><code>## Error: geom_line requires the following missing aesthetics: x and y</code></pre>
<p>Here is another example of plotting data from two different data frames:</p>
<pre class="r"><code>ggplot() +
geom_line(data=iris, aes(x = Sepal.Length, y=Petal.Length)) +
geom_bar(data=mtcars, aes(x=cyl), alpha=0.3) +
ylab("y") + xlab("x")</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-22-1.png" width="672" /></p>
</div>
<div id="adding-a-legend" class="section level2">
<h2>Adding a legend</h2>
<p>ggplot makes it rather hard to modify your legend if you create a plot this way. Creating a manual legend, as opposed to dynamically as ggplot is supposed to work, can be quite hacky. First thing to know is that the color, linestyle, and/or shape must be in <code>aes()</code> to appear in the legend. If it’s not there you can’t control it in the legend.</p>
<p>Note: What I am about to show <em>is really hacky and not the way ggplot is intended to be used,</em> but it comes up so often for new ggplot users that I want you to see a solution so you don’t give up on ggplot because of legends. Jump ahead to the correct ggplot workflow with long-form data frames to see how to avoid this.</p>
<p>This works. Ignore the warning about unknown aesthetics.</p>
<pre class="r"><code>ggplot() +
geom_point(data=df, aes(x=x, y=val, col="df", linetype="df")) +
geom_line(data=df2, aes(x=x, y=val2, col="df2", linetype="df2")) +
scale_color_manual("name", values=c("blue", "black")) +
scale_linetype_manual("name",values=c(0,1))</code></pre>
<pre><code>## Warning: Ignoring unknown aesthetics: linetype</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-23-1.png" width="672" /></p>
</div>
</div>
<div id="better-ggplot-workflow" class="section level1">
<h1>Better ggplot workflow</h1>
<p>This is how <code>ggplot()</code> is intended to be used</p>
<ul>
<li>Make data frames with <code>df</code> and <code>df2</code> data and a “name” column.</li>
<li>Set up the plot with <code>ggplot()</code></li>
<li>Make points or line different using the “name” column</li>
</ul>
<pre class="r"><code>df1 <- data.frame(x=x, val=val, name="df1")
df2 <- data.frame(x=x, val=val+10, name="df2")
df3 <- rbind(df1, df2)
ggplot(df3, aes(x=x, y=val, col=name, shape=name)) +
geom_line() +
geom_point()</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-24-1.png" width="672" /></p>
<div id="notes" class="section level2">
<h2>Notes</h2>
<ul>
<li>If the color, shape, linetype is not in an <code>aes()</code> it won’t appear in the legend.</li>
<li>If the color, shape, or linetype is in an <code>aes()</code> it will appear in the legend.</li>
<li><code>aes()</code> info in <code>ggplot()</code> flows to the other elements. Put the <code>aes()</code> info in the individual <code>geom_...()</code> calls if you don’t want that. Use <code>inherit.aes=FALSE</code> to stop this inheriting behavior.</li>
<li>Want to mix points and lines? You need to use <code>scale_..._manual()</code> to manually turn-off points or lines for some of the data.</li>
<li>You can always force colors, shapes, linetypes by passing in color, shape, size etc outside of <code>aes()</code> but it won’t appear in the legend. Only colors, shapes, etc, that appear in <code>aes()</code> will appear in a legend.</li>
</ul>
<p>Example, points are all black since the <code>aes(col=name)</code> only appears in the <code>geom_line()</code> call.</p>
<pre class="r"><code>ggplot(df3, aes(x=x, y=val)) +
geom_line(aes(col=name)) +
geom_point(aes(shape=name))</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-25-1.png" width="672" /></p>
</div>
<div id="modifying-the-legend" class="section level2">
<h2>Modifying the legend</h2>
<p>You can control all aspects of the legend. Read up on it <a href="http://www.cookbook-r.com/Graphs/Legends_(ggplot2)/">here</a>.</p>
<p>Manually changing data points and other lines will require <code>scale_...()</code> and gets hacky.</p>
<pre class="r"><code>ggplot(df3, aes(x=x, y=val)) +
geom_line(aes(col=name, linetype=name)) +
geom_point(aes(shape=name)) +
scale_color_manual("name", values=c("blue", "black")) +
scale_shape_manual("name",values=c(NA,1)) +
scale_linetype_manual("name",values=c(1,0))</code></pre>
<pre><code>## Warning: Removed 32 rows containing missing values (geom_point).</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-26-1.png" width="672" /></p>
</div>
<div id="na-warnings" class="section level2">
<h2>NA warnings</h2>
<p>Ack all those NA warnings!</p>
<pre class="r"><code>df4 <- data.frame(x=1:10, y=c(1,NA,NA,4:10), name=rep(c("a","b"),5))
ggplot(df4, aes(x=x, y=y, col=name)) +
geom_point()</code></pre>
<pre><code>## Warning: Removed 2 rows containing missing values (geom_point).</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-27-1.png" width="672" /></p>
<p>Get rid of them using <code>na.rm=TRUE</code>.</p>
<pre class="r"><code>ggplot(df4, aes(x=x, y=y, col=name)) +
geom_point(na.rm=TRUE)</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-28-1.png" width="672" /></p>
</div>
</div>
<div id="arranging-plots-into-grids" class="section level1">
<h1>Arranging plots into grids</h1>
<div id="manually" class="section level2">
<h2>Manually</h2>
<p>Let’s do a 4x4 grid of plots with <code>plot()</code>.</p>
<pre class="r"><code>par(mfrow=c(2,2))
t <- 1:10
val <- rnorm(10)
plot(t, val, type="b")
plot(t, val+100, type="l")
plot(t, 100*val, type="p")
barplot(1:4, 1:4, type="b")</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-29-1.png" width="672" /></p>
<p>Now let’s do this in with <code>ggplot()</code> in a similar workflow. The difference with <code>ggplot()</code> is that we save the plots and then arrange them into a grid with <code>gridExtra::grid.arrange()</code> (from the gridExtra package).</p>
<p><strong>UPDATE</strong> Instead of <strong>gridExtra</strong> and <code>grid.arrange()</code>, check out the <a href="https://cran.r-project.org/package=patchwork"><strong>patchwork</strong></a> package. It does similar jobs as <code>grid.arrange()</code> but is better.</p>
<p>Let’s do a 4x4 grid of plots with <code>plot()</code>.</p>
<pre class="r"><code>library(gridExtra)
df <- data.frame(t = 1:10, val = rnorm(10))
p1 <- ggplot(df, aes(x=t, y=val)) + geom_line() + geom_point()
p2 <- ggplot(df, aes(x=t, y=val+100)) + geom_line()
p3 <- ggplot(df, aes(x=t, y=100*val)) + geom_point()
df2 <- data.frame(t = 1:4, val = 1:4, se=.1*(1:4))
p4 <- ggplot(df2, aes(x=t, y=val)) + geom_col()
gridExtra::grid.arrange(p1, p2, p3, p4)</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-30-1.png" width="672" /></p>
<p>Let’s do two plots in one column but add new info to plot 1.</p>
<pre class="r"><code>gridExtra::grid.arrange(p1+geom_smooth(method="lm"),
p4+geom_errorbar(aes(ymin=val-se, ymax=val+se), width=0.3), ncol=1)</code></pre>
<pre><code>## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-31-1.png" width="672" /></p>
<p>When you don’t know how many plots you’ll be arranging. There are many situations where you are building a group of plots into a list and you don’t know how big that list will be (because the data flowing to your plot code changes). You can assemble ggplot objects into a list and pass that to <code>grid.arrange()</code>.</p>
<pre class="r"><code>df <- data.frame(t = 1:10, val = rnorm(10))
plist <- list()
n <- 3
for(i in 1:n) plist[[i]] <- ggplot(df, aes(x=t, y=val)) + geom_line() + geom_point()
df2 <- data.frame(t = 1:4, val = 1:4, se=.1*(1:4))
plist[[n+1]] <- ggplot(df2, aes(x=t, y=val)) + geom_col()
gridExtra::grid.arrange(grobs=plist)</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-32-1.png" width="672" /></p>
<p>The <strong>patchwork</strong> package gives you the same functionality.</p>
<pre><code>patchwork::wrap_plots(plist)</code></pre>
</div>
<div id="dynamically" class="section level2">
<h2>Dynamically</h2>
<p><code>ggplot()</code> will also dynamically break your data into plots for you.</p>
<pre class="r"><code>df1 <- data.frame(t=t, val=val, name="df1")
df2 <- data.frame(t=t, val=val+1, name="df2")
df <- rbind(df1, df2)
p1 <- ggplot(df, aes(x=t, y=val, col=name)) + geom_line()
p1</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-33-1.png" width="672" /></p>
<pre class="r"><code>p1 + facet_wrap(~name)</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-34-1.png" width="672" /></p>
<pre class="r"><code>head(mpg)</code></pre>
<pre><code>## # A tibble: 6 × 11
## manufacturer model displ year cyl trans drv cty hwy fl class
## <chr> <chr> <dbl> <int> <int> <chr> <chr> <int> <int> <chr> <chr>
## 1 audi a4 1.8 1999 4 auto(l5) f 18 29 p compa…
## 2 audi a4 1.8 1999 4 manual(m5) f 21 29 p compa…
## 3 audi a4 2 2008 4 manual(m6) f 20 31 p compa…
## 4 audi a4 2 2008 4 auto(av) f 21 30 p compa…
## 5 audi a4 2.8 1999 6 auto(l5) f 16 26 p compa…
## 6 audi a4 2.8 1999 6 manual(m5) f 18 26 p compa…</code></pre>
<p>Let’s plot city mpg versus number of cylinders.</p>
<pre class="r"><code>pc <- ggplot(mpg, aes(x=cyl, y=cty)) + geom_point()
pc</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-36-1.png" width="672" /></p>
<p>Now we can divide this up by different factors in our the mpg data frame.</p>
<pre class="r"><code>pc + facet_wrap(~class)</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-37-1.png" width="672" /></p>
<p>We can add some things to our plot and free the scales.</p>
<pre class="r"><code>pc + facet_wrap(~class, scales="free") + geom_smooth(method="lm")</code></pre>
<pre><code>## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-38-1.png" width="672" /></p>
<p>Another nice feature is that we can combine these wrapped figures into a grid because they are ggplot objects. Making this plot in base R would take you forever and another 2 forever is you wanted to change it around or if the number of classes in your data changed.</p>
<pre class="r"><code>pf <- pc + facet_wrap(~class)
grid.arrange( p1, pf, ncol=2)</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-39-1.png" width="672" /></p>
<p>And I can add features to the plots right in the <code>grid.arrange()</code> call.</p>
<pre class="r"><code>pf <- pc + facet_wrap(~class)
grid.arrange(
p1+ggtitle("All the classes"),
pf+theme_bw()+ylab("City mpg"),
ncol=2)</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-40-1.png" width="672" /></p>
</div>
<div id="notes-1" class="section level2">
<h2>Notes</h2>
<ul>
<li><code>facet_wrap()</code> often balks if you use different data frames in your plot construction, i.e. you doing something kind of hacky.
<ul>
<li>needs a column in your data frame factors (or characters it can coerce into factors). Might work with multiple data frames in your plot as long as each data frame has the same “name” column.</li>
<li>wants all the data frame to be the same length. This is only when you use different data frames. Fine if you have all data in one data frame.</li>
</ul></li>
</ul>
</div>
</div>
<div id="creating-plot-templates" class="section level1">
<h1>Creating plot templates</h1>
<p>If you are creating plots with the same features over and over, you can hold the features in a list and add that on to your plot.</p>
<p>Example where I want all my plots to have red points and a regression line:</p>
<pre class="r"><code>p3 <- geom_point(col="red")
p2 <- geom_smooth(method="lm")
p4 <- xlab("MPG")
p5 <- ylab("HP")
# pt is my template
pt <- list(p2, p3, p4, p5)
p1 <- ggplot(mtcars, aes(x=mpg, y=hp)) + pt
p2 <- ggplot(mpg, aes(x=hwy,y=cyl)) + pt
grid.arrange(p1, p2)</code></pre>
<pre><code>## `geom_smooth()` using formula 'y ~ x'
## `geom_smooth()` using formula 'y ~ x'</code></pre>
<p><img src="week5-ggplot2_files/figure-html/unnamed-chunk-41-1.png" width="672" /></p>
</div>
<div id="summary" class="section level1">
<h1>Summary</h1>
<p>ggplot can make your plotting workflow more efficient and much much faster. No more hassling with layouts. It takes a little while to get the hang of, but you do not need to be a ggplot wizard. Just the basics here will take you a long way. Google will answer any other questions that you have.</p>
<p>A good set of basic ggplot commands when you are starting:</p>
<ul>
<li><code>ggplot</code></li>
<li><code>geom_line()</code></li>
<li><code>geom_point()</code></li>
<li><code>geom_col()</code></li>
<li><code>ggtitle()</code>, <code>xlab()</code>, <code>ylab()</code>, <code>xlim()</code>, <code>ylim()</code></li>
<li>Themes. Use <code>?theme_bw</code> to see them.</li>
<li><code>gridExtra::grid.arrange(..., nrow, ncol)</code></li>
<li><code>facet_wrap()</code></li>
<li>Changing the color, line, and points manually is a bit painful, but often unavoidable. Get to know the <code>scale_xyz_manual()</code> functions when you need to do that. <code>?scale_color_manual</code> to find them all.</li>
</ul>
<p>ggplot’s main downside for me is the lack of a manual legend function like <code>plot()</code>’s <code>legend()</code> and the amount of work needed to customize legends. But this is made up for in ggplot’s other great features.</p>
</div>
<hr>
<div style="text-align: center">
<i class="fas fa-cubes"></i> NWFSC Math Bio Program <i class="fas fa-cubes"></i>
</div>
</div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.odd').parent('tbody').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
$(document).ready(function () {
$('.tabset-dropdown > .nav-tabs > li').click(function () {
$(this).parent().toggleClass('nav-tabs-open');
});
});
</script>
<!-- code folding -->
<script>
$(document).ready(function () {
// temporarily add toc-ignore selector to headers for the consistency with Pandoc
$('.unlisted.unnumbered').addClass('toc-ignore')
// move toc-ignore selectors from section div to header
$('div.section.toc-ignore')
.removeClass('toc-ignore')
.children('h1,h2,h3,h4,h5').addClass('toc-ignore');
// establish options
var options = {
selectors: "h1,h2",
theme: "bootstrap3",
context: '.toc-content',
hashGenerator: function (text) {
return text.replace(/[.\\/?&!#<>]/g, '').replace(/\s/g, '_');
},
ignoreSelector: ".toc-ignore",
scrollTo: 0
};
options.showAndHide = false;
options.smoothScroll = true;
// tocify
var toc = $("#TOC").tocify(options).data("toc-tocify");
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://mathjax.rstudio.com/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>