forked from datacarpentry/R-ecology-lesson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path05-visualization-ggplot2.html
453 lines (407 loc) · 33.3 KB
/
05-visualization-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
<!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>
<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 src="libs/navigation-1.1/tabsets.js"></script>
<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>
<h3 class="subtitle"><em>Visualizing data in R with the ggplot2 package</em></h3>
</div>
<div id="TOC">
<ul>
<li><a href="#plotting-with-ggplot2">Plotting with ggplot2</a></li>
<li><a href="#building-your-plots-iteratively">Building your plots iteratively</a></li>
<li><a href="#boxplot">Boxplot</a></li>
<li><a href="#plotting-time-series-data">Plotting time series data</a></li>
<li><a href="#faceting">Faceting</a></li>
<li><a href="#challenge">Challenge</a></li>
<li><a href="#customization">Customization</a></li>
</ul>
</div>
<div id="disclaimer" class="section level4">
<h4>Disclaimer</h4>
<p>We will be using the functions in the ggplot2 package. R has powerful built-in plotting capabilities, but for this exercise, we will be using the ggplot2 package, which facilitates the creation of highly-informative plots of structured data.</p>
<blockquote>
<h3 id="learning-objectives">Learning Objectives</h3>
<p>By the end of this lesson the learner will:</p>
<ul>
<li>Be able to create a ggplot object</li>
<li>Be able to set universal plot settings</li>
<li>Be able to modify an existing ggplot object</li>
<li>Be able to change the aesthetics of a plot such as colour</li>
<li>Be able to edit the axis labels</li>
<li>Know how to use a step-by-step approach to build complex plots</li>
<li>Be able to create, scatter plots, box plots and time series plots</li>
<li>Use the facet_wrap and facet_grid commands to create a collection of plots splitting the data by a factor variable</li>
<li>Be able to create customized plot styles to meet their needs</li>
</ul>
</blockquote>
<p>We start by loading the required packages.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># plotting package</span>
<span class="kw">library</span>(ggplot2)
<span class="co"># modern data frame manipulations</span>
<span class="kw">library</span>(dplyr)</code></pre></div>
<pre><code>#>
#> Attaching package: 'dplyr'</code></pre>
<pre><code>#> The following objects are masked from 'package:stats':
#>
#> filter, lag</code></pre>
<pre><code>#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union</code></pre>
</div>
<div id="plotting-with-ggplot2" class="section level2">
<h2>Plotting with ggplot2</h2>
<p>We will make the same plot using the <code>ggplot2</code> package.</p>
<p><code>ggplot2</code> is a plotting package that makes it simple to create complex plots from data in a dataframe. It uses default settings, which help creating publication quality plots with a minimal amount of settings and tweaking.</p>
<p>ggplot graphics are built step by step by adding new elements.</p>
<p>To build a ggplot we need to:</p>
<ul>
<li>bind the plot to a specific data frame using the <code>data</code> argument</li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> surveys_complete)</code></pre></div>
<ul>
<li>define aesthetics (<code>aes</code>), by selecting the variables to be plotted and the variables to define the presentation such as plotting size, shape color, etc.,</li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> surveys_complete, <span class="kw">aes</span>(<span class="dt">x =</span> weight, <span class="dt">y =</span> hindfoot_length))</code></pre></div>
<ul>
<li>add <code>geoms</code> – graphical representation of the data in the plot (points, lines, bars). To add a geom to the plot use <code>+</code> operator:</li>
</ul>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> surveys_complete, <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>The <code>+</code> in the <code>ggplot2</code> package is particularly useful because it allows you to modify existing <code>ggplot</code> objects. This means you can easily set up plot “templates” and conveniently explore different types of plots, so the above plot can also be generated with code like this:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Create</span>
surveys_plot <-<span class="st"> </span><span class="kw">ggplot</span>(<span class="dt">data =</span> surveys_complete, <span class="kw">aes</span>(<span class="dt">x =</span> weight, <span class="dt">y =</span> hindfoot_length))
<span class="co"># Draw the plot</span>
surveys_plot +<span class="st"> </span><span class="kw">geom_point</span>()</code></pre></div>
<p>Notes:</p>
<ul>
<li>Anything you put in the <code>ggplot()</code> function can be seen by any geom layers that you add (i.e., these are universal plot settings). This includes the x and y axis you set up in <code>aes()</code>.</li>
<li>You can also specify aesthetics for a given geom independently of the aesthetics defined globally in the <code>ggplot()</code> function.</li>
</ul>
</div>
<div id="building-your-plots-iteratively" class="section level2">
<h2>Building your plots iteratively</h2>
<p>Building plots with ggplot is typically an iterative process. We start by defining the dataset we’ll use, lay the axes, and choose a geom.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> surveys_complete, <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-create-ggplot-object-1.png" width="672" /></p>
<p>Then, we start modifying this plot to extract more information from it. For instance, we can add transparency (alpha) to avoid overplotting.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> surveys_complete, <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="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>
<p>We can also add colors for all the points</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> surveys_complete, <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="dt">alpha =</span> <span class="fl">0.1</span>, <span class="dt">color =</span> <span class="st">"blue"</span>)</code></pre></div>
<p><img src="img/R-ecology-adding-colors-1.png" width="672" /></p>
<p>Or to color each species in the plot differently:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> surveys_complete, <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="dt">alpha =</span> <span class="fl">0.1</span>, <span class="kw">aes</span>(<span class="dt">color=</span>species_id))</code></pre></div>
<p><img src="img/R-ecology-color-by-species-1.png" width="672" /></p>
</div>
<div id="boxplot" class="section level2">
<h2>Boxplot</h2>
<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>(<span class="dt">data =</span> surveys_complete, <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>(<span class="dt">data =</span> surveys_complete, <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>
<blockquote>
<h3 id="challenges">Challenges</h3>
<p>Boxplots are useful summaries, but hide the <em>shape</em> of the distribution. For example, if there is a bimodal distribution, this would not be observed with a boxplot. An alternative to the boxplot is the violin plot (sometimes known as a beanplot), where the shape (of the density of points) is drawn.</p>
<ul>
<li>Replace the box plot with a violin plot; see <code>geom_violin()</code></li>
</ul>
<p>In many types of data, it is important to consider the <em>scale</em> of the observations. For example, it may be worth changing the scale of the axis to better distribute the observations in the space of the plot. Changing the scale of the axes is done similarly to adding/modifying other components (i.e., by incrementally adding commands).</p>
<ul>
<li><p>Represent weight on the log10 scale; see <code>scale_y_log10()</code></p></li>
<li><p>Create boxplot for <code>hindfoot_length</code>.</p></li>
</ul>
</blockquote>
<blockquote>
<ul>
<li>Add color to the datapoints on your boxplot according to the plot from which the sample was taken (<code>plot_id</code>)</li>
</ul>
</blockquote>
<p>hint: Check the class for <code>plot_id</code>. Consider changing the class of <code>plot_id</code> from integer to factor. Why does this change how R makes the graph?</p>
</div>
<div id="plotting-time-series-data" class="section level2">
<h2>Plotting time series data</h2>
<p>Let’s calculate number of counts per year for each species. To do that we need to group data first and count records within each group.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">yearly_counts <-<span class="st"> </span>surveys_complete %>%
<span class="st"> </span><span class="kw">group_by</span>(year, species_id) %>%
<span class="st"> </span>tally</code></pre></div>
<p>Timelapse data can be visualised as a line plot with years on x axis and counts on y axis.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> yearly_counts, <span class="kw">aes</span>(<span class="dt">x =</span> year, <span class="dt">y =</span> n)) +
<span class="st"> </span><span class="kw">geom_line</span>()</code></pre></div>
<p><img src="img/R-ecology-first-time-series-1.png" width="672" /></p>
<p>Unfortunately this does not work, because we plot data for all the species together. We need to tell ggplot to draw a line for each species by modifying the aesthetic function to include <code>group = species_id</code>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</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="st"> </span><span class="kw">geom_line</span>()</code></pre></div>
<p><img src="img/R-ecology-time-series-by-species-1.png" width="672" /></p>
<p>We will be able to distinguish species in the plot if we add colors.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</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>()</code></pre></div>
<p><img src="img/R-ecology-time-series-with-colors-1.png" width="672" /></p>
</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"><span class="kw">ggplot</span>(<span class="dt">data =</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 year, species_id, and sex:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"> yearly_sex_counts <-<span class="st"> </span>surveys_complete %>%
<span class="st"> </span><span class="kw">group_by</span>(year, species_id, sex) %>%
<span class="st"> </span>tally</code></pre></div>
<p>We can now make the faceted plot splitting further by sex (within a single plot):</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"> <span class="kw">ggplot</span>(<span class="dt">data =</span> yearly_sex_counts, <span class="kw">aes</span>(<span class="dt">x =</span> year, <span class="dt">y =</span> n, <span class="dt">color =</span> species_id, <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-facet-by-species-and-sex-1.png" width="672" /></p>
<p>Usually plots with white background look more readable when printed. We can set the background to white using the function <code>theme_bw()</code>. Additionally you can also remove the grid.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"> <span class="kw">ggplot</span>(<span class="dt">data =</span> yearly_sex_counts, <span class="kw">aes</span>(<span class="dt">x =</span> year, <span class="dt">y =</span> n, <span class="dt">color =</span> species_id, <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) +
<span class="st"> </span><span class="kw">theme_bw</span>() +
<span class="st"> </span><span class="kw">theme</span>(<span class="dt">panel.grid.major.x =</span> <span class="kw">element_blank</span>(),
<span class="dt">panel.grid.minor.x =</span> <span class="kw">element_blank</span>(),
<span class="dt">panel.grid.major.y =</span> <span class="kw">element_blank</span>(),
<span class="dt">panel.grid.minor.y =</span> <span class="kw">element_blank</span>())</code></pre></div>
<p><img src="img/R-ecology-facet-by-species-and-sex-white-bg-1.png" width="672" /></p>
<p>To make the plot easier to read, we can color by sex instead of species (species are already in separate plots, so we don’t need to distinguish them further).</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> yearly_sex_counts, <span class="kw">aes</span>(<span class="dt">x =</span> year, <span class="dt">y =</span> n, <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) +
<span class="st"> </span><span class="kw">theme_bw</span>()</code></pre></div>
<p><img src="img/R-ecology-facet-by-species-and-sex-colored-1.png" width="672" /></p>
</div>
<div id="challenge" class="section level2">
<h2>Challenge</h2>
<blockquote>
<p>Use what you just learned to create a plot that depicts how the average weight of each species changes through the years.</p>
</blockquote>
<!-- Answer
```r
yearly_weight <- surveys_complete %>%
group_by(year, species_id) %>%
summarise(avg_weight = mean(weight))
ggplot(data = yearly_weight, aes(x=year, y=avg_weight, color = species_id, group = species_id)) +
geom_line() +
facet_wrap(~ species_id) +
theme_bw()
```
<img src="img/R-ecology-average-weight-timeseries-1.png" width="672" />
-->
<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>
<p>Let’s modify the previous plot to compare how the weights of male and females has changed through time.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">## One column, facet by rows
yearly_sex_weight <-<span class="st"> </span>surveys_complete %>%
<span class="st"> </span><span class="kw">group_by</span>(year, sex, species_id) %>%
<span class="st"> </span><span class="kw">summarize</span>(<span class="dt">avg_weight =</span> <span class="kw">mean</span>(weight))
<span class="kw">ggplot</span>(<span class="dt">data =</span> yearly_sex_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_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>
<span class="kw">ggplot</span>(<span class="dt">data =</span> yearly_sex_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_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>
<div id="customization" class="section level2">
<h2>Customization</h2>
<p>Take a look at the ggplot2 cheat sheet (<a href="https://www.rstudio.com/wp-content/uploads/2015/08/ggplot2-cheatsheet.pdf" class="uri">https://www.rstudio.com/wp-content/uploads/2015/08/ggplot2-cheatsheet.pdf</a>), and think of ways to improve the plot. You can write down some of your ideas as comments in the Etherpad.</p>
<p>Now, let’s change names of axes to something more informative than ‘year’ and ‘n’ and add a title to this figure:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> yearly_sex_counts, <span class="kw">aes</span>(<span class="dt">x =</span> year, <span class="dt">y =</span> n, <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) +
<span class="st"> </span><span class="kw">labs</span>(<span class="dt">title =</span> <span class="st">'Observed species in time'</span>,
<span class="dt">x =</span> <span class="st">'Year of observation'</span>,
<span class="dt">y =</span> <span class="st">'Number of species'</span>) +
<span class="st"> </span><span class="kw">theme_bw</span>()</code></pre></div>
<p><img src="img/R-ecology-number_species_year_with_right_labels-1.png" width="672" /></p>
<p>The axes have more informative names, but their readability can be improved by increasing the font size. While we are at it, we’ll also change the font family:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> yearly_sex_counts, <span class="kw">aes</span>(<span class="dt">x =</span> year, <span class="dt">y =</span> n, <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) +
<span class="st"> </span><span class="kw">labs</span>(<span class="dt">title =</span> <span class="st">'Observed species in time'</span>,
<span class="dt">x =</span> <span class="st">'Year of observation'</span>,
<span class="dt">y =</span> <span class="st">'Number of species'</span>) +
<span class="st"> </span><span class="kw">theme_bw</span>() +
<span class="st"> </span><span class="kw">theme</span>(<span class="dt">text=</span><span class="kw">element_text</span>(<span class="dt">size=</span><span class="dv">16</span>, <span class="dt">family=</span><span class="st">"Arial"</span>))</code></pre></div>
<p><img src="img/R-ecology-number_species_year_with_right_labels_xfont_size-1.png" width="672" /></p>
<p>After our manipulations we notice that the values on the x-axis are still not properly readable. Let’s change the orientation of the labels and adjust them vertically and horizontally so they don’t overlap. You can use a 90 degree angle, or experiment to find the appropriate angle for diagonally oriented labels.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">ggplot</span>(<span class="dt">data =</span> yearly_sex_counts, <span class="kw">aes</span>(<span class="dt">x =</span> year, <span class="dt">y =</span> n, <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) +
<span class="st"> </span><span class="kw">labs</span>(<span class="dt">title =</span> <span class="st">'Observed species in time'</span>,
<span class="dt">x =</span> <span class="st">'Year of observation'</span>,
<span class="dt">y =</span> <span class="st">'Number of species'</span>) +
<span class="st"> </span><span class="kw">theme_bw</span>() +
<span class="st"> </span><span class="kw">theme</span>(<span class="dt">axis.text.x =</span> <span class="kw">element_text</span>(<span class="dt">colour=</span><span class="st">"grey20"</span>, <span class="dt">size=</span><span class="dv">12</span>, <span class="dt">angle=</span><span class="dv">90</span>, <span class="dt">hjust=</span>.<span class="dv">5</span>, <span class="dt">vjust=</span>.<span class="dv">5</span>),
<span class="dt">axis.text.y =</span> <span class="kw">element_text</span>(<span class="dt">colour=</span><span class="st">"grey20"</span>, <span class="dt">size=</span><span class="dv">12</span>),
<span class="dt">text=</span><span class="kw">element_text</span>(<span class="dt">size=</span><span class="dv">16</span>, <span class="dt">family=</span><span class="st">"Arial"</span>))</code></pre></div>
<p><img src="img/R-ecology-number_species_year_with_theme-1.png" width="672" /></p>
<p>If you like the changes you created to the default theme, you can save them as an object to easily apply them to other plots you may create:</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">arial_grey_theme <-<span class="st"> </span><span class="kw">theme</span>(<span class="dt">axis.text.x =</span> <span class="kw">element_text</span>(<span class="dt">colour=</span><span class="st">"grey20"</span>, <span class="dt">size=</span><span class="dv">12</span>, <span class="dt">angle=</span><span class="dv">90</span>, <span class="dt">hjust=</span>.<span class="dv">5</span>, <span class="dt">vjust=</span>.<span class="dv">5</span>),
<span class="dt">axis.text.y =</span> <span class="kw">element_text</span>(<span class="dt">colour=</span><span class="st">"grey20"</span>, <span class="dt">size=</span><span class="dv">12</span>),
<span class="dt">text=</span><span class="kw">element_text</span>(<span class="dt">size=</span><span class="dv">16</span>, <span class="dt">family=</span><span class="st">"Arial"</span>))
<span class="kw">ggplot</span>(surveys_complete, <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="st"> </span>arial_grey_theme</code></pre></div>
<p><img src="img/R-ecology-number_species_year_with_right_labels_xfont_orientation-1.png" width="672" /></p>
<p>With all of this information in hand, please take another five minutes to either improve one of the plots generated in this exercise or create a beautiful graph of your own. Use the RStudio ggplot2 cheat sheet, which we linked earlier for inspiration.</p>
<p>Here are some ideas:</p>
<ul>
<li>See if you can change thickness of the lines.</li>
<li>Can you find a way to change the name of the legend? What about its labels?</li>
<li>Use a different color palette (see <a href="http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/" class="uri">http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/</a>)</li>
</ul>
<p>After creating your plot, you can save it to a file in your favourite format. You can easily change the dimension (and its resolution) of your plot by adjusting the appropriate arguments (<code>width</code>, <code>height</code> and <code>dpi</code>):</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">my_plot <-<span class="st"> </span><span class="kw">ggplot</span>(<span class="dt">data =</span> yearly_sex_counts, <span class="kw">aes</span>(<span class="dt">x =</span> year, <span class="dt">y =</span> n, <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) +
<span class="st"> </span><span class="kw">labs</span>(<span class="dt">title =</span> <span class="st">'Observed species in time'</span>,
<span class="dt">x =</span> <span class="st">'Year of observation'</span>,
<span class="dt">y =</span> <span class="st">'Number of species'</span>) +
<span class="st"> </span><span class="kw">theme_bw</span>() +
<span class="st"> </span><span class="kw">theme</span>(<span class="dt">axis.text.x =</span> <span class="kw">element_text</span>(<span class="dt">colour=</span><span class="st">"grey20"</span>, <span class="dt">size=</span><span class="dv">12</span>, <span class="dt">angle=</span><span class="dv">90</span>, <span class="dt">hjust=</span>.<span class="dv">5</span>, <span class="dt">vjust=</span>.<span class="dv">5</span>),
<span class="dt">axis.text.y =</span> <span class="kw">element_text</span>(<span class="dt">colour=</span><span class="st">"grey20"</span>, <span class="dt">size=</span><span class="dv">12</span>),
<span class="dt">text=</span><span class="kw">element_text</span>(<span class="dt">size=</span><span class="dv">16</span>, <span class="dt">family=</span><span class="st">"Arial"</span>))
<span class="kw">ggsave</span>(<span class="st">"name_of_file.png"</span>, my_plot, <span class="dt">width=</span><span class="dv">15</span>, <span class="dt">height=</span><span class="dv">10</span>)</code></pre></div>
</div>
</div>
<script>
// add bootstrap table styles to pandoc tables
$(document).ready(function () {
$('tr.header').parent('thead').parent('table').addClass('table table-condensed');
});
</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>