-
Notifications
You must be signed in to change notification settings - Fork 3
/
03-ggplot2.html
468 lines (422 loc) · 34.1 KB
/
03-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
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="generator" content="pandoc" />
<title>Data visualization with ggplot2</title>
<script src="libs/jquery-1.11.3/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="libs/bootstrap-3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<script src="libs/bootstrap-3.3.5/js/bootstrap.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/html5shiv.min.js"></script>
<script src="libs/bootstrap-3.3.5/shim/respond.min.js"></script>
<script src="libs/navigation-1.1/tabsets.js"></script>
<style type="text/css">code{white-space: pre;}</style>
<style type="text/css">
div.sourceCode { overflow-x: auto; }
table.sourceCode, tr.sourceCode, td.lineNumbers, td.sourceCode {
margin: 0; padding: 0; vertical-align: baseline; border: none; }
table.sourceCode { width: 100%; line-height: 100%; background-color: #f8f8f8; }
td.lineNumbers { text-align: right; padding-right: 4px; padding-left: 4px; color: #aaaaaa; border-right: 1px solid #aaaaaa; }
td.sourceCode { padding-left: 5px; }
pre, code { background-color: #f8f8f8; }
code > span.kw { color: #204a87; font-weight: bold; } /* Keyword */
code > span.dt { color: #204a87; } /* DataType */
code > span.dv { color: #0000cf; } /* DecVal */
code > span.bn { color: #0000cf; } /* BaseN */
code > span.fl { color: #0000cf; } /* Float */
code > span.ch { color: #4e9a06; } /* Char */
code > span.st { color: #4e9a06; } /* String */
code > span.co { color: #8f5902; font-style: italic; } /* Comment */
code > span.ot { color: #8f5902; } /* Other */
code > span.al { color: #ef2929; } /* Alert */
code > span.fu { color: #000000; } /* Function */
code > span.er { color: #a40000; font-weight: bold; } /* Error */
code > span.wa { color: #8f5902; font-weight: bold; font-style: italic; } /* Warning */
code > span.cn { color: #000000; } /* Constant */
code > span.sc { color: #000000; } /* SpecialChar */
code > span.vs { color: #4e9a06; } /* VerbatimString */
code > span.ss { color: #4e9a06; } /* SpecialString */
code > span.im { } /* Import */
code > span.va { color: #000000; } /* Variable */
code > span.cf { color: #204a87; font-weight: bold; } /* ControlFlow */
code > span.op { color: #ce5c00; font-weight: bold; } /* Operator */
code > span.pp { color: #8f5902; font-style: italic; } /* Preprocessor */
code > span.ex { } /* Extension */
code > span.at { color: #c4a000; } /* Attribute */
code > span.do { color: #8f5902; font-weight: bold; font-style: italic; } /* Documentation */
code > span.an { color: #8f5902; font-weight: bold; font-style: italic; } /* Annotation */
code > span.cv { color: #8f5902; font-weight: bold; font-style: italic; } /* CommentVar */
code > span.in { color: #8f5902; font-weight: bold; font-style: italic; } /* Information */
</style>
<style type="text/css">
pre:not([class]) {
background-color: white;
}
</style>
<style type="text/css">
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;
}
.table th:not([align]) {
text-align: left;
}
</style>
</head>
<body>
<style type = "text/css">
.main-container {
max-width: 940px;
margin-left: auto;
margin-right: auto;
}
code {
color: inherit;
background-color: rgba(0, 0, 0, 0.04);
}
img {
max-width:100%;
height: auto;
}
.tabbed-pane {
padding-top: 12px;
}
button.code-folding-btn:focus {
outline: none;
}
</style>
<div class="container-fluid main-container">
<!-- tabsets -->
<script>
$(document).ready(function () {
window.buildTabsets("TOC");
});
</script>
<!-- code folding -->
<div class="fluid-row" id="header">
<h1 class="title toc-ignore">Data visualization with ggplot2</h1>
</div>
<div id="TOC">
<ul>
<li><a href="#plotting-with-ggplot2">Plotting with ggplot2</a><ul>
<li><a href="#challenge">Challenge</a></li>
</ul></li>
<li><a href="#other-aesthetics">Other aesthetics</a><ul>
<li><a href="#challenge-1">Challenge</a></li>
</ul></li>
<li><a href="#layers">Layers</a><ul>
<li><a href="#challenge-2">Challenge</a></li>
</ul></li>
<li><a href="#groups">Groups</a></li>
<li><a href="#univariate-geoms">Univariate geoms</a><ul>
<li><a href="#challenge-3">Challenge</a></li>
<li><a href="#boxplot">Boxplot</a></li>
<li><a href="#challenge-4">Challenge</a></li>
</ul></li>
<li><a href="#faceting">Faceting</a><ul>
<li><a href="#challenge-5">Challenge</a></li>
<li><a href="#facet_grid">facet_grid</a></li>
</ul></li>
<li><a href="#saving-plots-to-a-file">Saving plots to a file</a></li>
<li><a href="#customizing-plots">Customizing plots</a><ul>
<li><a href="#axis-limits">Axis limits</a></li>
<li><a href="#color-choices">Color choices</a></li>
</ul></li>
<li><a href="#themes">Themes</a></li>
</ul>
</div>
<blockquote>
<h3 id="learning-objectives">Learning Objectives</h3>
<ul>
<li>Visualize some of the <a href="https://dx.doi.org/10.6084/m9.figshare.1314459.v5">mammals data</a> from <a href="http://kbroman.org/datacarp/portal_data_joined.csv"><code>portal_data_joined.csv</code></a></li>
<li>Understand how to plot these data using R ggplot2 package. For more details on using ggplot2 see <a href="http://docs.ggplot2.org/current/">official documentation</a>.</li>
<li>Building step by step complex plots with the ggplot2 package</li>
</ul>
</blockquote>
<p>I’ve placed these reduced data on the web, so you can download them directly.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">reduced <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"http://kbroman.org/datacarp/portal_data_reduced.csv"</span>)</code></pre></div>
<p>Or download the file and then load it</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">download.file</span>(<span class="st">"http://kbroman.org/datacarp/portal_data_reduced.csv"</span>,
<span class="st">"CleanData/portal_data_reduced.csv"</span>)
reduced <-<span class="st"> </span><span class="kw">read.csv</span>(<span class="st">"CleanData/portal_data_reduced.csv"</span>)</code></pre></div>
<div id="plotting-with-ggplot2" class="section level2">
<h2>Plotting with ggplot2</h2>
<p>There are two main systems for making plots in R: “base graphics” (which are the traditional plotting functions distributed with R) and ggplot2, written by Hadley Wickham following Leland Wilkinson’s book <em>Grammar of Graphics</em>. We’re going to show you how to use ggplot2. It’s may seem a bit complicated at first, but once you get a hang of it, you’ll be able to make really useful visualizations quite rapidly.</p>
<p>We first need to load the dplyr and ggplot2 packages.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(ggplot2)
<span class="kw">library</span>(dplyr)</code></pre></div>
<p>I’ll assume the data are available, and we’ll focus on the “cleaned” version, <code>reduced</code>.</p>
<p>Let’s first make a scatterplot of hindfoot length vs weight. Here’s the code to do it.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(reduced, <span class="kw">aes</span>(<span class="dt">x =</span> weight, <span class="dt">y =</span> hindfoot_length)) +<span class="st"> </span><span class="kw">geom_point</span>()</code></pre></div>
<p><img src="img/R-ecology-first-ggplot-1.png" width="672" /></p>
<p>Two key concepts in the grammar of graphics: <em>aesthetics</em> map features of the data (for example, the <code>weight</code> variable) to features of the visualization (for example the y-axis coordinate), and <em>geoms</em> concern what actually gets plotted (here, each row in the data becomes a point in the plot).</p>
<p>Another key aspect of ggplot2: the <code>ggplot()</code> function creates a graphics object; additional controls are added with the <code>+</code> operator. The actual plot is made when the object is printed.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p1 <-<span class="st"> </span><span class="kw">ggplot</span>(reduced, <span class="kw">aes</span>(<span class="dt">x=</span>weight, <span class="dt">y=</span>hindfoot_length))
p2 <-<span class="st"> </span>p1 +<span class="st"> </span><span class="kw">geom_point</span>()
<span class="kw">print</span>(p2)</code></pre></div>
<p>If we saved the pieces like this, we could apply other options afterwards. For example, if we wanted <code>weight</code> on a log scale:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p2 +<span class="st"> </span><span class="kw">scale_x_log10</span>()</code></pre></div>
<p><img src="img/R-ecology-weight_on_log_scale-1.png" width="672" /></p>
<p>This makes it kind of easy to try out different things. For example, we could plot the x-axis on a square root scale.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p2 +<span class="st"> </span><span class="kw">scale_x_sqrt</span>()</code></pre></div>
<p><img src="img/R-ecology-weight_on_sqrt_scale-1.png" width="672" /></p>
<div id="challenge" class="section level3">
<h3>Challenge</h3>
<p>Make a scatterplot of <code>hindfoot_length</code> vs <code>weight</code>, but only for the <code>species_id</code>, <code>"DM"</code>.</p>
<!-- end challenge -->
</div>
</div>
<div id="other-aesthetics" class="section level2">
<h2>Other aesthetics</h2>
<p>For scatterplot, additional aesthetics include <code>shape</code>, <code>size</code>, <code>color</code>, and “<code>alpha</code>” (for transparency of points).</p>
<p>Let’s make a template for our plot, to make modifications easier.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">surveys_plot <-<span class="st"> </span><span class="kw">ggplot</span>(reduced, <span class="kw">aes</span>(<span class="dt">x =</span> weight, <span class="dt">y =</span> hindfoot_length))</code></pre></div>
<ul>
<li>adding transparency (alpha)</li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">surveys_plot +<span class="st"> </span><span class="kw">geom_point</span>(<span class="dt">alpha =</span> <span class="fl">0.1</span>)</code></pre></div>
<p><img src="img/R-ecology-adding-transparency-1.png" width="672" /></p>
<ul>
<li>adding colors</li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">surveys_plot +<span class="st"> </span><span class="kw">geom_point</span>(<span class="dt">alpha =</span> <span class="fl">0.1</span>, <span class="dt">color =</span> <span class="st">"slateblue"</span>)</code></pre></div>
<p><img src="img/R-ecology-adding-colors-1.png" width="672" /></p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">surveys_plot +<span class="st"> </span><span class="kw">geom_point</span>(<span class="dt">alpha =</span> <span class="fl">0.1</span>, <span class="dt">color =</span> <span class="st">"slateblue"</span>, <span class="dt">size=</span><span class="fl">0.5</span>)</code></pre></div>
<p><img src="img/R-ecology-changing%20the%20size%20of%20the%20points-1.png" width="672" /></p>
<p>Things get more interesting when we assign these aesthetics to data.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">surveys_plot +<span class="st"> </span><span class="kw">geom_point</span>(<span class="kw">aes</span>(<span class="dt">color =</span> species_id))</code></pre></div>
<p><img src="img/R-ecology-scatter_colored_by_species-1.png" width="672" /></p>
<div id="challenge-1" class="section level3">
<h3>Challenge</h3>
<p>Use dplyr to calculate the mean <code>weight</code> and <code>hindfoot_length</code> as well as the sample size for each species.</p>
<p>Make a scatterplot of mean <code>hindfoot_length</code> vs mean <code>weight</code>, with the sizes of the points corresponding to the sample size.</p>
<!-- end challenge -->
</div>
</div>
<div id="layers" class="section level2">
<h2>Layers</h2>
<p>You can use <code>geom_line</code> to make a line plot. For example, we could plot the counts of species by year.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">count_by_year <-<span class="st"> </span>reduced %>%
<span class="st"> </span><span class="kw">group_by</span>(year) %>%
<span class="st"> </span>tally
p <-<span class="st"> </span><span class="kw">ggplot</span>(count_by_year, <span class="kw">aes</span>(<span class="dt">x=</span>year, <span class="dt">y=</span>n))
p +<span class="st"> </span><span class="kw">geom_line</span>()</code></pre></div>
<p><img src="img/R-ecology-plot_counts_by_year-1.png" width="672" /></p>
<p>You can use <em>both</em> <code>geom_line</code> and <code>geom_point</code> to make a line plot with points at the data values.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p +<span class="st"> </span><span class="kw">geom_line</span>() +<span class="st"> </span><span class="kw">geom_point</span>()</code></pre></div>
<p><img src="img/R-ecology-line_plus_point-1.png" width="672" /></p>
<p>This brings up another important concept with ggplot2: <em>layers</em>. A given plot can have multiple layers of geometric objects, plotted one on top of the other.</p>
<p>If you make the lines and points different colors, we can see that the points are placed <em>on top</em> of the lines.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p +<span class="st"> </span><span class="kw">geom_line</span>(<span class="dt">color=</span><span class="st">"lightblue"</span>) +<span class="st"> </span><span class="kw">geom_point</span>(<span class="dt">color=</span><span class="st">"violetred"</span>)</code></pre></div>
<p><img src="img/R-ecology-line_plus_point_wcolors-1.png" width="672" /></p>
<p>If we switch the order of <code>geom_point</code> and <code>geom_line</code>, we’ll reverse the layers.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p +<span class="st"> </span><span class="kw">geom_point</span>(<span class="dt">color=</span><span class="st">"violetred"</span>) +<span class="st"> </span><span class="kw">geom_line</span>(<span class="dt">color=</span><span class="st">"lightblue"</span>)</code></pre></div>
<p><img src="img/R-ecology-line_plus_point_wcolors_alt-1.png" width="672" /></p>
<p>Note that aesthetics included in the call to <code>ggplot()</code> (or completely separately) are made to be the defaults for all layers, but we can separately control the aesthetics for each layer. For example, we could color the points by year:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p +<span class="st"> </span><span class="kw">geom_line</span>() +<span class="st"> </span><span class="kw">geom_point</span>(<span class="kw">aes</span>(<span class="dt">color=</span>year))</code></pre></div>
<p><img src="img/R-ecology-points_colored_by_year-1.png" width="672" /></p>
<p>Compare that to the following:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p +<span class="st"> </span><span class="kw">geom_line</span>() +<span class="st"> </span><span class="kw">geom_point</span>() +<span class="st"> </span><span class="kw">aes</span>(<span class="dt">color=</span>year)</code></pre></div>
<p><img src="img/R-ecology-points_colored_by_year_2-1.png" width="672" /></p>
<div id="challenge-2" class="section level3">
<h3>Challenge</h3>
<p>Make a plot of counts of <code>species_id</code> <code>"DM"</code> and <code>"DS"</code> by year.</p>
<!-- end challenge -->
</div>
</div>
<div id="groups" class="section level2">
<h2>Groups</h2>
<p>Suppose, in that last challenge, we’d wanted to have black lines but the points colored by species. We might have done this:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">counts_dm_ds <-<span class="st"> </span>reduced %>%<span class="st"> </span><span class="kw">filter</span>(species_id %in%<span class="st"> </span><span class="kw">c</span>(<span class="st">"DM"</span>, <span class="st">"DS"</span>)) %>%
<span class="st"> </span><span class="kw">group_by</span>(species_id, year) %>%<span class="st"> </span>tally
p <-<span class="st"> </span><span class="kw">ggplot</span>(counts_dm_ds, <span class="kw">aes</span>(<span class="dt">x=</span>year, <span class="dt">y=</span>n))
p +<span class="st"> </span><span class="kw">geom_line</span>() +<span class="st"> </span><span class="kw">geom_point</span>(<span class="kw">aes</span>(<span class="dt">color=</span>species_id))</code></pre></div>
<p><img src="img/R-ecology-misgrouped-1.png" width="672" /></p>
<p>The points get connected left-to-right, which is not what we want.</p>
<p>If we make the <code>color=species_id</code> aesthetic <em>global</em>, we don’t have this problem.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p +<span class="st"> </span><span class="kw">geom_line</span>() +<span class="st"> </span><span class="kw">geom_point</span>() +<span class="st"> </span><span class="kw">aes</span>(<span class="dt">color=</span>species_id)</code></pre></div>
<p><img src="img/R-ecology-color_global-1.png" width="672" /></p>
<p>Alternatively, we can use the <code>group</code> aesthetic, which indicates that certain data points go together. This way the lines can be a constant color.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p +<span class="st"> </span><span class="kw">geom_line</span>(<span class="kw">aes</span>(<span class="dt">group=</span>species_id)) +<span class="st"> </span><span class="kw">geom_point</span>(<span class="kw">aes</span>(<span class="dt">color=</span>species_id))</code></pre></div>
<p><img src="img/R-ecology-group_aes-1.png" width="672" /></p>
<p>We could also make the group aesthetic global</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p +<span class="st"> </span><span class="kw">aes</span>(<span class="dt">group=</span>species_id) +<span class="st"> </span><span class="kw">geom_line</span>() +<span class="st"> </span><span class="kw">geom_point</span>(<span class="kw">aes</span>(<span class="dt">color=</span>species_id))</code></pre></div>
<p><img src="img/R-ecology-group_global-1.png" width="672" /></p>
</div>
<div id="univariate-geoms" class="section level2">
<h2>Univariate geoms</h2>
<p>We’ve focused so far on scatterplots, but one can also create one-dimensional summaries, such as histograms or boxplots.</p>
<div id="challenge-3" class="section level3">
<h3>Challenge</h3>
<p>Try using <code>geom_histogram()</code> to make a histogram visualization of the distribution of <code>weight</code>.</p>
<p>Hint: You want <code>weight</code> as the x-axis aesthetic. Try specifying <code>bins</code> in <code>geom_histogram()</code>.</p>
<!-- end challenge -->
</div>
<div id="boxplot" class="section level3">
<h3>Boxplot</h3>
<p>Visualising the distribution of weight within each species.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(reduced, <span class="kw">aes</span>(<span class="dt">x =</span> species_id, <span class="dt">y =</span> hindfoot_length)) +
<span class="st"> </span><span class="kw">geom_boxplot</span>()</code></pre></div>
<p><img src="img/R-ecology-boxplot-1.png" width="672" /></p>
<p>By adding points to boxplot, we can have a better idea of the number of measurements and of their distribution:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(reduced, <span class="kw">aes</span>(<span class="dt">x =</span> species_id, <span class="dt">y =</span> hindfoot_length)) +
<span class="st"> </span><span class="kw">geom_boxplot</span>(<span class="dt">alpha =</span> <span class="dv">0</span>) +
<span class="st"> </span><span class="kw">geom_jitter</span>(<span class="dt">alpha =</span> <span class="fl">0.3</span>, <span class="dt">color =</span> <span class="st">"tomato"</span>)</code></pre></div>
<p><img src="img/R-ecology-boxplot-with-points-1.png" width="672" /></p>
<p>Notice how the boxplot layer is behind the jitter layer? What do you need to change in the code to put the boxplot in front of the points such that it’s not hidden.</p>
</div>
<div id="challenge-4" class="section level3">
<h3>Challenge</h3>
<p>A variant on the box plot is the violin plot. Use <code>geom_violin()</code> to make violin plots of <code>hindfoot_length</code> by <code>species_id</code>.</p>
<!-- end challenge -->
</div>
</div>
<div id="faceting" class="section level2">
<h2>Faceting</h2>
<p>ggplot has a special technique called <em>faceting</em> that allows to split one plot into multiple plots based on a factor included in the dataset. We will use it to make one plot for a time series for each species.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">yearly_counts <-<span class="st"> </span>reduced %>%<span class="st"> </span><span class="kw">group_by</span>(year, species_id) %>%<span class="st"> </span>tally
<span class="kw">ggplot</span>(yearly_counts, <span class="kw">aes</span>(<span class="dt">x =</span> year, <span class="dt">y =</span> n, <span class="dt">group =</span> species_id, <span class="dt">colour =</span> species_id)) +
<span class="st"> </span><span class="kw">geom_line</span>() +
<span class="st"> </span><span class="kw">facet_wrap</span>(~<span class="st"> </span>species_id)</code></pre></div>
<p><img src="img/R-ecology-first-facet-1.png" width="672" /></p>
<p>Now we would like to split line in each plot by sex of each individual measured. To do that we need to make counts in data frame grouped by sex.</p>
<div id="challenge-5" class="section level3">
<h3>Challenge</h3>
<ul>
<li><p>Calculate counts grouped by year, species_id, and sex</p></li>
<li><p>make the faceted plot splitting further by sex (within each panel)</p></li>
<li><p>color by sex rather than species</p></li>
</ul>
<!-- end challenge -->
<p>Suppose I make a similar plot of average weight by species:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">yearly_weight <-<span class="st"> </span>reduced %>%
<span class="st"> </span><span class="kw">group_by</span>(year, species_id, sex) %>%
<span class="st"> </span><span class="kw">summarise</span>(<span class="dt">avg_weight =</span> <span class="kw">mean</span>(weight, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>))
<span class="kw">ggplot</span>(yearly_weight, <span class="kw">aes</span>(<span class="dt">x=</span>year, <span class="dt">y=</span>avg_weight, <span class="dt">color =</span> species_id, <span class="dt">group =</span> species_id)) +
<span class="st"> </span><span class="kw">geom_line</span>() +
<span class="st"> </span><span class="kw">facet_wrap</span>(~<span class="st"> </span>species_id)</code></pre></div>
<p><img src="img/R-ecology-average-weight-timeseries-1.png" width="672" /></p>
<p>Why do we see those steps in the plot?</p>
<p><strong>Oops</strong> need to group by sex</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">yearly_weight <-<span class="st"> </span>reduced %>%
<span class="st"> </span><span class="kw">group_by</span>(year, species_id, sex) %>%
<span class="st"> </span><span class="kw">summarise</span>(<span class="dt">avg_weight =</span> <span class="kw">mean</span>(weight, <span class="dt">na.rm =</span> <span class="ot">TRUE</span>))
<span class="kw">ggplot</span>(yearly_weight, <span class="kw">aes</span>(<span class="dt">x=</span>year, <span class="dt">y=</span>avg_weight, <span class="dt">color =</span> sex, <span class="dt">group =</span> sex)) +
<span class="st"> </span><span class="kw">geom_line</span>() +
<span class="st"> </span><span class="kw">facet_wrap</span>(~<span class="st"> </span>species_id)</code></pre></div>
<p><img src="img/R-ecology-average-weight-timeseries-fixed-1.png" width="672" /></p>
</div>
<div id="facet_grid" class="section level3">
<h3>facet_grid</h3>
<p>The <code>facet_wrap</code> geometry extracts plots into an arbitrary number of dimensions to allow them to cleanly fit on one page. On the other hand, the <code>facet_grid</code> geometry allows you to explicitly specify how you want your plots to be arranged via formula notation (<code>rows ~ columns</code>; a <code>.</code> can be used as a placeholder that indicates only one row or column).</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">## One column, facet by rows
yearly_weight %>%<span class="st"> </span><span class="kw">filter</span>(species_id %in%<span class="st"> </span><span class="kw">c</span>(<span class="st">"DM"</span>, <span class="st">"DO"</span>, <span class="st">"DS"</span>)) %>%
<span class="st"> </span><span class="kw">ggplot</span>(<span class="kw">aes</span>(<span class="dt">x=</span>year, <span class="dt">y=</span>avg_weight, <span class="dt">color =</span> species_id, <span class="dt">group =</span> species_id)) +
<span class="st"> </span><span class="kw">geom_line</span>() +
<span class="st"> </span><span class="kw">facet_grid</span>(sex ~<span class="st"> </span>.)</code></pre></div>
<p><img src="img/R-ecology-average-weight-time-facet_sex_rows-1.png" width="672" /></p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># One row, facet by column</span>
yearly_weight %>%<span class="st"> </span><span class="kw">filter</span>(species_id %in%<span class="st"> </span><span class="kw">c</span>(<span class="st">"DM"</span>, <span class="st">"DO"</span>, <span class="st">"DS"</span>)) %>%
<span class="st"> </span><span class="kw">ggplot</span>(<span class="kw">aes</span>(<span class="dt">x=</span>year, <span class="dt">y=</span>avg_weight, <span class="dt">color =</span> species_id, <span class="dt">group =</span> species_id)) +
<span class="st"> </span><span class="kw">geom_line</span>() +
<span class="st"> </span><span class="kw">facet_grid</span>( ~<span class="st"> </span>sex)</code></pre></div>
<p><img src="img/R-ecology-average-weight-time-facet_sex_columns-1.png" width="672" /></p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># separate panel for each sex and species</span>
yearly_weight %>%<span class="st"> </span><span class="kw">filter</span>(species_id %in%<span class="st"> </span><span class="kw">c</span>(<span class="st">"DM"</span>, <span class="st">"DO"</span>, <span class="st">"DS"</span>)) %>%
<span class="st"> </span><span class="kw">ggplot</span>(<span class="kw">aes</span>(<span class="dt">x=</span>year, <span class="dt">y=</span>avg_weight, <span class="dt">color =</span> species_id, <span class="dt">group =</span> species_id)) +
<span class="st"> </span><span class="kw">geom_line</span>() +
<span class="st"> </span><span class="kw">facet_grid</span>(species_id ~<span class="st"> </span>sex)</code></pre></div>
<p><img src="img/R-ecology-average-weight-time-facet_sex_columns_species_rows-1.png" width="672" /></p>
</div>
</div>
<div id="saving-plots-to-a-file" class="section level2">
<h2>Saving plots to a file</h2>
<p>If you want to save a plot, to share with others, use the <code>ggsave</code> function.</p>
<p>The default is to save the last plot that you created, but I think it’s safer to first save the plot as an object and pass that to <code>ggsave</code>. Also give the height and width in inches.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p <-<span class="st"> </span><span class="kw">ggplot</span>(reduced, <span class="kw">aes</span>(<span class="dt">x=</span>weight, <span class="dt">y=</span>hindfoot_length)) +<span class="st"> </span><span class="kw">geom_point</span>()
<span class="kw">ggsave</span>(<span class="st">"scatter.png"</span>, p, <span class="dt">height=</span><span class="dv">6</span>, <span class="dt">width=</span><span class="dv">8</span>)</code></pre></div>
<p>The image file type is taken from the file name extension. To make a PDF instead:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggsave</span>(<span class="st">"scatter.pdf"</span>, p, <span class="dt">height=</span><span class="dv">6</span>, <span class="dt">width=</span><span class="dv">8</span>)</code></pre></div>
<p>Use <code>scale</code> to adjust the sizes of things, for example for a talk/poster versus a paper/report. Use <code>scale < 1</code> to make the various elements bigger relative to the plotting area.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggsave</span>(<span class="st">"scatter_2.png"</span>, p, <span class="dt">height=</span><span class="dv">6</span>, <span class="dt">width=</span><span class="dv">8</span>, <span class="dt">scale=</span><span class="fl">0.8</span>)</code></pre></div>
</div>
<div id="customizing-plots" class="section level2">
<h2>Customizing plots</h2>
<div id="axis-limits" class="section level3">
<h3>Axis limits</h3>
<p>When faceting, the different panels are given common x- and y-axis limits. If we were to create separate plots (say one for each country), we would need to do a bit extra to ensure that common axis limits are used.</p>
<p>Recall the <code>scale_x_log10()</code> function that we had used to create the log scale for the x axis. This can take an argument <code>limits</code> (a vector of length 2) defining the minimum and maximum values plotted.</p>
<p>There is also a <code>scale_y_log10()</code> function, but if you want to change the y-axis limits without going to a log scale, you would use <code>scale_y_continuous()</code>. (Similarly, there’s a <code>scale_x_continuous</code>.)</p>
<p>For example, to plot the data for China, using axis limits defined by the full data, we’d do the following:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">xrange <-<span class="st"> </span><span class="kw">range</span>(reduced$weight)
yrange <-<span class="st"> </span><span class="kw">range</span>(reduced$hindfoot_length)
p <-<span class="st"> </span>reduced %>%<span class="st"> </span><span class="kw">filter</span>(species_id==<span class="st">"DM"</span>) %>%
<span class="st"> </span><span class="kw">ggplot</span>(<span class="kw">aes</span>(<span class="dt">x=</span>weight, <span class="dt">y=</span>hindfoot_length)) +
<span class="st"> </span><span class="kw">geom_point</span>()
p +<span class="st"> </span><span class="kw">scale_x_log10</span>(<span class="dt">limits=</span>xrange) +
<span class="st"> </span><span class="kw">scale_y_continuous</span>(<span class="dt">limits=</span>yrange)</code></pre></div>
<p><img src="img/R-ecology-limits-1.png" width="672" /></p>
</div>
<div id="color-choices" class="section level3">
<h3>Color choices</h3>
<p>If you don’t like the choices for point colors, you can customize them in a number of ways. First, you can use <code>scale_color_manual()</code> with a vector of your preferred choices. (If it’s <code>fill</code> rather than <code>color</code> that you want to change, you’ll need to use <code>scale_fill_manual()</code>.)</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p <-<span class="st"> </span>reduced %>%<span class="st"> </span><span class="kw">filter</span>(species_id %in%<span class="st"> </span><span class="kw">c</span>(<span class="st">"DM"</span>, <span class="st">"DS"</span>, <span class="st">"DO"</span>)) %>%
<span class="st"> </span><span class="kw">ggplot</span>(<span class="kw">aes</span>(<span class="dt">x=</span>weight, <span class="dt">y=</span>hindfoot_length)) +
<span class="st"> </span><span class="kw">geom_point</span>(<span class="kw">aes</span>(<span class="dt">color=</span>species_id))
colors <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"blue"</span>, <span class="st">"green"</span>, <span class="st">"orange"</span>)
p +<span class="st"> </span><span class="kw">scale_color_manual</span>(<span class="dt">values=</span>colors)</code></pre></div>
<p><img src="img/R-ecology-custom_colors-1.png" width="672" /></p>
<p>You can also use RGB hex values.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">hexcolors <-<span class="st"> </span><span class="kw">c</span>(<span class="st">"#001F3F"</span>, <span class="st">"#0074D9"</span>, <span class="st">"#01FF70"</span>)
p +<span class="st"> </span><span class="kw">scale_color_manual</span>(<span class="dt">values=</span>hexcolors)</code></pre></div>
<p><img src="img/R-ecology-custom_colors_rgb-1.png" width="672" /></p>
</div>
</div>
<div id="themes" class="section level2">
<h2>Themes</h2>
<p>Not everyone gray background and such in the default ggplot plots.</p>
<p>But you can apply one of a variety of “themes” to control the overall appearance of plots.</p>
<p>One that a lot of people like is <code>theme_bw()</code>. Add it to a plot, and the overall appearance changes.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">p +<span class="st"> </span><span class="kw">theme_bw</span>()</code></pre></div>
<p><img src="img/R-ecology-theme-1.png" width="672" /></p>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
function bootstrapStylePandocTables() {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
}
$(document).ready(function () {
bootstrapStylePandocTables();
});
</script>
<!-- dynamically load mathjax for compatibility with self-contained -->
<script>
(function () {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML";
document.getElementsByTagName("head")[0].appendChild(script);
})();
</script>
</body>
</html>