forked from datacarpentry/R-ecology-lesson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path04-visualization-ggplot2.Rmd
501 lines (396 loc) · 17.8 KB
/
04-visualization-ggplot2.Rmd
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
---
title: Data visualization with ggplot2
author: Data Carpentry contributors
minutes: 60
---
```{r setup, echo=FALSE, purl=FALSE}
source("setup.R")
surveys_complete <- read.csv(file = "data_output/surveys_complete.csv")
```
```{r, echo=FALSE, purl=TRUE}
### Data Visualization with ggplot2
```
------------
> ### Learning Objectives
>
> * Produce scatter plots, boxplots, and time series plots using ggplot.
> * Set universal plot settings.
> * Modify the aesthetics of an existing ggplot plot (including axis labels and color).
> * Build complex and customized plots from data in a data frame.
--------------
We start by loading the required packages.
```{r load-package, message=FALSE, purl=FALSE}
library(tidyverse)
```
## Plotting with **`ggplot2`**
**`ggplot2`** is a plotting package that makes it simple to create complex plots
from data in a data frame. It provides a more programmatic interface for
specifying what variables to plot, how they are displayed, and general visual
properties, so we only need minimal changes if the underlying data change or if
we decide to change from a bar plot to a scatterplot. This helps in creating
publication quality plots with minimal amounts of adjustments and tweaking.
ggplot graphics are built step by step by adding new elements.
To build a ggplot we need to:
- bind the plot to a specific data frame using the `data` argument
```{r, eval=FALSE, purl=FALSE}
ggplot(data = surveys_complete)
```
- define aesthetics (`aes`), by selecting the variables to be plotted and the variables to define the presentation
such as plotting size, shape color, etc.
```{r, eval=FALSE, purl=FALSE}
ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length))
```
- add `geoms` -- graphical representation of the data in the plot (points,
lines, bars). To add a geom to the plot use `+` operator
```{r first-ggplot, purl=FALSE}
ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length)) +
geom_point()
```
The `+` in the **`ggplot2`** package is particularly useful because it allows you
to modify existing `ggplot` 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:
```{r, first-ggplot-with-plus, eval=FALSE, purl=FALSE}
# Assign plot to a variable
surveys_plot <- ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length))
# Draw the plot
surveys_plot + geom_point()
```
```{r, eval=FALSE, purl=TRUE, echo=FALSE, purl=FALSE}
## Create a ggplot and draw it.
surveys_plot <- ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length))
surveys_plot + geom_point()
```
Notes:
- Anything you put in the `ggplot()` 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 `aes()`.
- You can also specify aesthetics for a given geom independently of the
aesthetics defined globally in the `ggplot()` function.
- The `+` sign used to add layers must be placed at the end of each line containing
a layer. If, instead, the `+` sign is added in the line before the other layer,
**`ggplot2`** will not add the new layer and will return an error message.
```{r, ggplot-with-plus-position, eval=FALSE, purl=FALSE}
# this is the correct syntax for adding layers
surveys_plot +
geom_point()
# this will not add the new layer and will return an error message
surveys_plot
+ geom_point()
```
> ### Challenge (optional)
>
> Scatter plots can be useful exploratory tools for small datasets. For data
> sets with large numbers of observations, such as the `surveys_complete` data
> set, overplotting of points can be a limitation of scatter plots. One strategy
> for handling such settings is to use hexagonal binning of observations. The
> plot space is tessellated into hexagons. Each hexagon is assigned a color
> based on the number of observations that fall within its boundaries. To use
> hexagonal binning with **`ggplot2`**, first install the R package `hexbin` from
> CRAN:
>
>
> ```{r, eval = FALSE}
> install.packages("hexbin")
> ```
>
> Then use `geom_hex()` function from the **`ggplot2`** package.
>
> ```{r, eval = FALSE}
> surveys_plot +
> geom_hex()
> ```
>
> - What are the relative strengths and weaknesses of a hexagonal bin plot
> compared to a scatter plot? Examine the above scatter plot and compare it
> with the hexagonal bin plot that you created.
## Building your plots iteratively
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:
```{r create-ggplot-object, purl=FALSE}
ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length)) +
geom_point()
```
Then, we start modifying this plot to extract more information from it. For
instance, we can add transparency (alpha) to avoid overplotting:
```{r adding-transparency, purl=FALSE}
ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length)) +
geom_point(alpha = 0.1)
```
We can also add colors for all the points:
```{r adding-colors, purl=FALSE}
ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length)) +
geom_point(alpha = 0.1, color = "blue")
```
Or to color each species in the plot differently:
```{r color-by-species, purl=FALSE}
ggplot(data = surveys_complete, aes(x = weight, y = hindfoot_length)) +
geom_point(alpha = 0.1, aes(color=species_id))
```
## Boxplot
We can use boxplots to visualize the distribution of weight within each species:
```{r boxplot, purl=FALSE}
ggplot(data = surveys_complete, aes(x = species_id, y = hindfoot_length)) +
geom_boxplot()
```
By adding points to boxplot, we can have a better idea of the number of
measurements and of their distribution:
```{r boxplot-with-points, purl=FALSE}
ggplot(data = surveys_complete, aes(x = species_id, y = hindfoot_length)) +
geom_boxplot(alpha = 0) +
geom_jitter(alpha = 0.3, color = "tomato")
```
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?
> ### Challenges (optional)
>
> Boxplots are useful summaries, but hide the *shape* of the distribution. For
> example, if there is a bimodal distribution, it 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.
>
> - Replace the box plot with a violin plot; see `geom_violin()`.
>
> In many types of data, it is important to consider the *scale* 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). Try making these modifications:
>
> - Represent weight on the log10 scale; see `scale_y_log10()`.
>
> - Create boxplot for `hindfoot_length`.
>
> - Add color to the datapoints on your boxplot according to the plot from which
> the sample was taken (`plot_id`).
Hint: Check the class for `plot_id`. Consider changing the class of `plot_id`
from integer to factor. Why does this change how R makes the graph?
```{r, eval=FALSE, purl=TRUE, echo=FALSE}
## Challenges:
## Start with the boxplot we created:
ggplot(data = surveys_complete, aes(x = species_id, y = hindfoot_length)) +
geom_boxplot(alpha = 0) +
geom_jitter(alpha = 0.3, color = "tomato")
## 1. Replace the box plot with a violin plot; see `geom_violin()`.
## 2. Represent weight on the log10 scale; see `scale_y_log10()`.
## 3. Create boxplot for `hindfoot_length`.
## 4. Add color to the datapoints on your boxplot according to the
## plot from which the sample was taken (`plot_id`).
## Hint: Check the class for `plot_id`. Consider changing the class
## of `plot_id` from integer to factor. Why does this change how R
## makes the graph?
```
## Plotting time series data
Let's calculate number of counts per year for each species. First we need
to group the data and count records within each group:
```{r, purl=FALSE}
yearly_counts <- surveys_complete %>%
group_by(year, species_id) %>%
tally
```
Timelapse data can be visualized as a line plot with years on the x axis and counts
on the y axis:
```{r first-time-series, purl=FALSE}
ggplot(data = yearly_counts, aes(x = year, y = n)) +
geom_line()
```
Unfortunately, this does not work because we plotted 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 `group = species_id`:
```{r time-series-by-species, purl=FALSE}
ggplot(data = yearly_counts, aes(x = year, y = n, group = species_id)) +
geom_line()
```
We will be able to distinguish species in the plot if we add colors:
```{r time-series-with-colors, purl=FALSE}
ggplot(data = yearly_counts, aes(x = year, y = n, group = species_id, colour = species_id)) +
geom_line()
```
## Faceting
ggplot has a special technique called *faceting* that allows the user to split one plot
into multiple plots based on a factor included in the dataset. We will use it to
make a time series plot for each species:
```{r first-facet, purl=FALSE}
ggplot(data = yearly_counts, aes(x = year, y = n, group = species_id, colour = species_id)) +
geom_line() +
facet_wrap(~ species_id)
```
Now we would like to split the line in each plot by the sex of each individual
measured. To do that we need to make counts in the data frame grouped by year,
species_id, and sex:
```{r, purl=FALSE}
yearly_sex_counts <- surveys_complete %>%
group_by(year, species_id, sex) %>%
tally
```
We can now make the faceted plot by splitting further by sex (within a single plot):
```{r facet-by-species-and-sex, purl=FALSE}
ggplot(data = yearly_sex_counts, aes(x = year, y = n, color = species_id, group = sex)) +
geom_line() +
facet_wrap(~ species_id)
```
Usually plots with white background look more readable when printed. We can set
the background to white using the function `theme_bw()`. Additionally, you can remove
the grid:
```{r facet-by-species-and-sex-white-bg, purl=FALSE}
ggplot(data = yearly_sex_counts, aes(x = year, y = n, color = species_id, group = sex)) +
geom_line() +
facet_wrap(~ species_id) +
theme_bw() +
theme(panel.grid.major.x = element_blank(),
panel.grid.minor.x = element_blank(),
panel.grid.major.y = element_blank(),
panel.grid.minor.y = element_blank())
```
## **`ggplot2`** themes
In addition to `theme_bw()`, which changes the plot background to white, **`ggplot2`**
comes with several other themes which can be useful to quickly change the look
of your visualization. The complete list of themes is available
at <http://docs.ggplot2.org/current/ggtheme.html>. `theme_minimal()` and
`theme_light()` are popular, and `theme_void()` can be useful as a starting
point to create a new hand-crafted theme.
The
[ggthemes](https://cran.r-project.org/web/packages/ggthemes/vignettes/ggthemes.html) package
provides a wide variety of options (including an Excel 2003 theme).
The [**`ggplot2`** extensions website](https://www.ggplot2-exts.org) provides a list
of packages that extend the capabilities of **`ggplot2`**, including additional
themes.
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):
```{r facet-by-species-and-sex-colored, purl=FALSE}
ggplot(data = yearly_sex_counts, aes(x = year, y = n, color = sex, group = sex)) +
geom_line() +
facet_wrap(~ species_id) +
theme_bw()
```
## Challenge (optional)
> Use what you just learned to create a plot that depicts how the average weight
> of each species changes through the years.
<!-- Answer
```{r average-weight-time-series, purl=FALSE}
yearly_weight <- surveys_complete %>%
group_by(year, species_id) %>%
summarize(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()
```
-->
```{r, eval=FALSE, purl=TRUE, echo=FALSE}
## Plotting time series challenge:
## Use what you just learned to create a plot that depicts how the
## average weight of each species changes through the years.
```
The `facet_wrap` geometry extracts plots into an arbitrary number of dimensions
to allow them to cleanly fit on one page. On the other hand, the `facet_grid`
geometry allows you to explicitly specify how you want your plots to be
arranged via formula notation (`rows ~ columns`; a `.` can be used as
a placeholder that indicates only one row or column).
Let's modify the previous plot to compare how the weights of male and females
has changed through time:
```{r average-weight-time-facet-sex-rows, purl=FALSE}
# One column, facet by rows
yearly_sex_weight <- surveys_complete %>%
group_by(year, sex, species_id) %>%
summarize(avg_weight = mean(weight))
ggplot(data = yearly_sex_weight, aes(x=year, y=avg_weight, color = species_id, group = species_id)) +
geom_line() +
facet_grid(sex ~ .)
```
```{r average-weight-time-facet-sex-columns, purl=FALSE}
# One row, facet by column
ggplot(data = yearly_sex_weight, aes(x=year, y=avg_weight, color = species_id, group = species_id)) +
geom_line() +
facet_grid(. ~ sex)
```
## Customization
Take a look at the [**`ggplot2`** cheat sheet](https://www.rstudio.com/wp-content/uploads/2016/11/ggplot2-cheatsheet-2.1.pdf), and
think of ways you could improve the plot.
Now, let's change names of axes to something more informative than 'year'
and 'n' and add a title to the figure:
```{r number-species-year-with-right-labels, purl=FALSE}
ggplot(data = yearly_sex_counts, aes(x = year, y = n, color = sex, group = sex)) +
geom_line() +
facet_wrap(~ species_id) +
labs(title = 'Observed species in time',
x = 'Year of observation',
y = 'Number of species') +
theme_bw()
```
The axes have more informative names, but their readability can be improved by
increasing the font size:
```{r number-species-year-with-right-labels-xfont-size, purl=FALSE}
ggplot(data = yearly_sex_counts, aes(x = year, y = n, color = sex, group = sex)) +
geom_line() +
facet_wrap(~ species_id) +
labs(title = 'Observed species in time',
x = 'Year of observation',
y = 'Number of species') +
theme_bw() +
theme(text=element_text(size=16))
```
Note that it is also possible to change the fonts of your plots. If you are on
Windows, you may have to install
the [**extrafont** package](https://github.com/wch/extrafont), and follow the
instructions included in the README for this package.
After our manipulations, you may 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:
```{r number-species-year-with-theme, purl=FALSE}
ggplot(data = yearly_sex_counts, aes(x = year, y = n, color = sex, group = sex)) +
geom_line() +
facet_wrap(~ species_id) +
labs(title = 'Observed species in time',
x = 'Year of observation',
y = 'Number of species') +
theme_bw() +
theme(axis.text.x = element_text(colour="grey20", size=12, angle=90, hjust=.5, vjust=.5),
axis.text.y = element_text(colour="grey20", size=12),
text=element_text(size=16))
```
If you like the changes you created better than the default theme, you can save them as
an object to be able to easily apply them to other plots you may create:
```{r number-species-year-with-right-labels-xfont-orientation, purl=FALSE}
grey_theme <- theme(axis.text.x = element_text(colour="grey20", size=12, angle=90, hjust=.5, vjust=.5),
axis.text.y = element_text(colour="grey20", size=12),
text=element_text(size=16))
ggplot(surveys_complete, aes(x = species_id, y = hindfoot_length)) +
geom_boxplot() +
grey_theme
```
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](https://www.rstudio.com/wp-content/uploads/2016/11/ggplot2-cheatsheet-2.1.pdf) for
inspiration.
Here are some ideas:
* See if you can change the thickness of the lines.
* Can you find a way to change the name of the legend? What about its labels?
* Try using a different color palette (see http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/).
After creating your plot, you can save it to a file in your favorite format.
You can easily change the dimension (and resolution) of your plot by
adjusting the appropriate arguments (`width`, `height` and `dpi`):
```{r ggsave-example, eval=FALSE, purl=FALSE}
my_plot <- ggplot(data = yearly_sex_counts, aes(x = year, y = n, color = sex, group = sex)) +
geom_line() +
facet_wrap(~ species_id) +
labs(title = 'Observed species in time',
x = 'Year of observation',
y = 'Number of species') +
theme_bw() +
theme(axis.text.x = element_text(colour="grey20", size=12, angle=90, hjust=.5, vjust=.5),
axis.text.y = element_text(colour="grey20", size=12),
text=element_text(size=16))
ggsave("name_of_file.png", my_plot, width=15, height=10)
```
```{r, eval=FALSE, purl=TRUE, echo=FALSE}
## Final plotting challenge:
## 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 for inspiration:
## https://www.rstudio.com/wp-content/uploads/2015/08/ggplot2-cheatsheet.pdf
```