You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: ggplot/index.qmd
+33-33Lines changed: 33 additions & 33 deletions
Original file line number
Diff line number
Diff line change
@@ -26,7 +26,7 @@ filters:
26
26
---
27
27
## Introduction
28
28
29
-
::: {.long-format}
29
+
::: {.narration}
30
30
While you can make plots with just the packages that come bundled with base R, many R users make their visualizations entirely using the [`ggplot2`](https://ggplot2.tidyverse.org/index.html) package and an [ecosystem of packages](https://exts.ggplot2.tidyverse.org/gallery/) designed around it.
31
31
:::
32
32
@@ -35,7 +35,7 @@ While you can make plots with just the packages that come bundled with base R, m
35
35
library(ggplot2)
36
36
```
37
37
38
-
::: {.long-format}
38
+
::: {.narration}
39
39
As with the previous sessions, we'll be using the Palmer penguins dataset. While we built our own combined dataset in the introduction session, now we're going to use the built-in cleaned dataset. First, let's load the dataset. Then let's inspect the data using the `glimpse()` function.
40
40
:::
41
41
@@ -44,21 +44,21 @@ data(penguins)
44
44
dplyr::glimpse(penguins)
45
45
```
46
46
47
-
::: {.long-format}
47
+
::: {.narration}
48
48
As we discovered before, this dataset includes many different measurements for individual penguins from three different studies. The studies cover both sexes of three different species of penguins from three different islands in the Palmer Archipelago.
49
49
:::
50
50
51
51
## The ggplot2 basics
52
52
53
-
::: {.long-format}
53
+
::: {.narration}
54
54
The most important function in the `ggplot2` package is `ggplot()`. Note that this function doesn't include the "2" of the package name. Let's go ahead and try using this function on our penguins data.
55
55
:::
56
56
57
57
```{r ggplot-raw}
58
58
ggplot(penguins)
59
59
```
60
60
61
-
::: {.long-format}
61
+
::: {.narration}
62
62
You'll notice that the `ggplot()` function doesn't actually do much by itself. Here, we provide it with the penguins dataset, but the result looks like someone started making a plot and then stopped after the first step of making the rectangle for the plot area. This is because `ggplot2` is designed around the "grammar of graphics". Therefore, it expects you to build a sentence-like structure out of its functions. A single word (i.e., the call to `ggplot()` above) doesn't make much of a sentence, so let's start building up a real sentence.
63
63
64
64
By using the `ggplot()` function, we are essentially stating that we are beginning a plotting "sentence". We then combine this with other "words" (function calls) using the `+` operator. The next component you usually want to specify in a `ggplot` "sentence" is our "aesthetic" mappings. These specify the columns of the dataset that correspond to each axis of the plot, including the x/y axes, but also the axes of color, shape, etc. We do this with the `aes()` function:
@@ -69,7 +69,7 @@ ggplot(penguins) +
69
69
aes(x = body_mass, y = flipper_len)
70
70
```
71
71
72
-
::: {.long-format}
72
+
::: {.narration}
73
73
Hey, it's starting to look like a plot now! Except there isn't any actual data being plotted. Let's fix that. We'll start off with a simple scatter plot by using the `geom_point()` function:
74
74
:::
75
75
@@ -79,7 +79,7 @@ ggplot(penguins) +
79
79
geom_point()
80
80
```
81
81
82
-
::: {.long-format}
82
+
::: {.narration}
83
83
And there we go! You'll notice that with just a few lines, we've already made a pretty nice visualization of this penguin data. `ggplot2` does most of the work for us once we specify our dataset and our `x` and `y` variables.
84
84
:::
85
85
@@ -96,7 +96,7 @@ penguins <- penguins |>
96
96
:::
97
97
::::
98
98
99
-
::: {.long-format}
99
+
::: {.narration}
100
100
Now, let's go a step further and color the points by another variable (e.g., the island of the penguins). With `ggplot2`, all that requires is specifying another aesthetic:
101
101
:::
102
102
@@ -106,7 +106,7 @@ ggplot(penguins) +
106
106
geom_point()
107
107
```
108
108
109
-
::: {.long-format}
109
+
::: {.narration}
110
110
Notice that `ggplot2` comes with its own default color scheme. However, I would strongly discourage you from using the default colors, especially as the number of categories increases (with only 3 categories here it isn't too bad). Let's try out some of the more accessible color palettes that are also available in R.
111
111
112
112
First, let's try one of the [`viridis`](https://cran.r-project.org/web/packages/viridis/vignettes/intro-to-viridis.html) color palettes. Since this palette is included in `ggplot2`, all we need to do is add the proper "scale" to our `ggplot()` call. Scales tell ggplot how to handle a particular aesthetic, and are usually of the form `scale_[aesthetic]_[type]()`.
@@ -119,7 +119,7 @@ ggplot(penguins) +
119
119
scale_color_viridis_d(end = 0.7) # avoid yellow at the end of the palette
120
120
```
121
121
122
-
::: {.long-format}
122
+
::: {.narration}
123
123
Now let's try one of the [brewer color palettes](https://r-graph-gallery.com/38-rcolorbrewers-palettes.html).
124
124
:::
125
125
@@ -130,7 +130,7 @@ ggplot(penguins) +
130
130
scale_color_brewer(palette = "Set1")
131
131
```
132
132
133
-
::: {.long-format}
133
+
::: {.narration}
134
134
Outside of color, there are many other [aspects of the graph](https://ggplot2.tidyverse.org/articles/ggplot2-specs.html) that we can modify using aesthetics and "scale"s. For example, we can modify the shape of the points:
135
135
:::
136
136
@@ -156,7 +156,7 @@ ggplot(penguins) +
156
156
```
157
157
:::
158
158
159
-
::: {.long-format}
159
+
::: {.narration}
160
160
And the x/y axes:
161
161
:::
162
162
@@ -173,7 +173,7 @@ ggplot(penguins) +
173
173
174
174
## Theming
175
175
176
-
::: {.long-format}
176
+
::: {.narration}
177
177
The last basic thing you might want to do with `ggplot2` is modify the style of the visualization. This is extremely customizable, but the first place to start is with a [built-in theme](https://ggplot2.tidyverse.org/reference/ggtheme.html). I personally prefer the classic theme, which looks very similar to base R plots:
178
178
:::
179
179
@@ -189,7 +189,7 @@ ggplot(penguins) +
189
189
theme_classic()
190
190
```
191
191
192
-
::: {.long-format}
192
+
::: {.narration}
193
193
Using this built-in theme has changed many visual aspects of the graph, including changing the plot background color, adding axis lines, and removing the internal grid lines. If you look very closely, however, the axis tick labels are still a slight grey. We can use the `theme()` function to further customize the appearance and change this. In this case, we'll make the axis text elements have a black color instead of the default gray.
194
194
:::
195
195
@@ -206,7 +206,7 @@ ggplot(penguins) +
206
206
theme(axis.text = element_text(color = "black"))
207
207
```
208
208
209
-
::: {.long-format}
209
+
::: {.narration}
210
210
And there we have it! With just 10 lines we've created what I would say is a publication quality graph! `ggplot` does a lot of the tedious work for us, giving us time to focus on the more important aspects, such as labeling and color. Admittedly, I've spent a LOT of time on these aspects in the past...
211
211
212
212
More information about all of the hierarchical theme components that you can customize is available [here](https://ggplot2.tidyverse.org/reference/theme.html). In order to change many of these components, you need to use theme elements like we did above with `element_text()`. That and other theme elements are documented [here](https://ggplot2.tidyverse.org/reference/element.html).
@@ -216,13 +216,13 @@ More information about all of the hierarchical theme components that you can cus
216
216
217
217
### Other layers
218
218
219
-
::: {.long-format}
219
+
::: {.narration}
220
220
There are many other [types of plots](https://ggplot2.tidyverse.org/reference/#layers) that we can make with `ggplot2`.
221
221
:::
222
222
223
223
#### Histograms
224
224
225
-
::: {.long-format}
225
+
::: {.narration}
226
226
We can visualize the density of values for a single variable with a histogram:
227
227
:::
228
228
@@ -248,7 +248,7 @@ ggplot(penguins) +
248
248
249
249
#### Boxplots and Violin Plotss
250
250
251
-
::: {.long-format}
251
+
::: {.narration}
252
252
We can visualize the density of values for a single variable across a discrete variable with boxplots or violin plots:
253
253
:::
254
254
@@ -275,7 +275,7 @@ Note that many of these "geom"s have lots of options. For example, here we've de
275
275
276
276
#### 2D Contours
277
277
278
-
::: {.long-format}
278
+
::: {.narration}
279
279
We can also visualize the density of values across two continuous variables using a 2D contour:
280
280
:::
281
281
@@ -287,7 +287,7 @@ ggplot(penguins) +
287
287
theme(axis.text = element_text(color = "black"))
288
288
```
289
289
290
-
::: {.long-format}
290
+
::: {.narration}
291
291
Note that sometimes you may need to expand the axes a little bit to better show the contours:
292
292
:::
293
293
@@ -302,7 +302,7 @@ ggplot(penguins) +
302
302
303
303
#### Time Series
304
304
305
-
::: {.long-format}
305
+
::: {.narration}
306
306
Since there isn't really any time series data in the penguins dataset, we'll take a quick detour and use the built-in `economics` dataset to explore visualizing a time series. In this case, we are looking at unemployment over time:
`geom_path()` lets you explore how two variables are related over time. For example, unemployment and personal savings rate:
318
318
:::
319
319
@@ -331,7 +331,7 @@ Note how we've used multiple columns of the data to define the x-axis here. You
331
331
332
332
### Combining layers
333
333
334
-
::: {.long-format}
334
+
::: {.narration}
335
335
We can also combine multiple layers to show the same data in different ways in the same plot. For example, we could show the raw data for the above contour plot in addition to the contours:
336
336
:::
337
337
@@ -355,7 +355,7 @@ When combining layers, the layers are added to the plot in order, so in this cas
355
355
356
356
### Facetting
357
357
358
-
::: {.long-format}
358
+
::: {.narration}
359
359
Let's take our scatterplot example from earlier:
360
360
:::
361
361
@@ -372,7 +372,7 @@ ggplot(penguins) +
372
372
theme(axis.text = element_text(color = "black"))
373
373
```
374
374
375
-
::: {.long-format}
375
+
::: {.narration}
376
376
Now, what if we wanted to also split the data by the species of the penguins? We're already using color and shape, so what other aesthetic could we use? We could possible use some shapes that have both a fill and outline color, but that sounds messy. Instead of using another aesthetic, we could also use a `facet`. This splits the chart into multiple panels:
377
377
:::
378
378
@@ -390,7 +390,7 @@ ggplot(penguins) +
390
390
theme(axis.text = element_text(color = "black"))
391
391
```
392
392
393
-
::: {.long-format}
393
+
::: {.narration}
394
394
We can get even crazier by faceting by multiple variables:
395
395
:::
396
396
@@ -408,21 +408,21 @@ ggplot(penguins) +
408
408
theme(axis.text = element_text(color = "black"))
409
409
```
410
410
411
-
::: {.long-format}
411
+
::: {.narration}
412
412
OK, maybe we've gone a little too far here, but you get the picture!
413
413
:::
414
414
415
415
## Combining plots
416
416
417
-
::: {.long-format}
417
+
::: {.narration}
418
418
When publishing results, often we need to combine multiple figures into a single visualization. There are lots of packages for accomplishing this (even my own [deeptime](https://williamgearty.com/deeptime) package has some functionality for it), but today we'll check out the [`patchwork`](https://patchwork.data-imaginist.com/) package which extends the "grammar of graphics" to combining plots (you may need to install it if you haven't done so already).
419
419
:::
420
420
421
421
```{r patchwork}
422
422
library(patchwork)
423
423
```
424
424
425
-
::: {.long-format}
425
+
::: {.narration}
426
426
First, let's go ahead and make some plots. Instead of plotting them, though, we'll save them as objects in our environment. Note that when you save a plot to an object it isn't displayed in the "Plots" tab.
427
427
:::
428
428
@@ -445,15 +445,15 @@ g2 <- ggplot(penguins) +
445
445
theme(axis.text = element_text(color = "black"))
446
446
```
447
447
448
-
::: {.long-format}
448
+
::: {.narration}
449
449
Now, in order to combine these, all we need to do is combine them using the `+` operator, like we did with the individual elements of the plots.
450
450
:::
451
451
452
452
```{r add-plots}
453
453
g1 + g2
454
454
```
455
455
456
-
::: {.long-format}
456
+
::: {.narration}
457
457
You can see that `patchwork` does all of the work for us, lining up the different components of the plots. If we have more plots to combine, we can then use the `|` (side-by-side) and `/` (above-and-below) operators to make more complex arrangements of plots.
458
458
:::
459
459
@@ -467,13 +467,13 @@ g3 <- ggplot(penguins) +
467
467
(g1 | g2) / g3
468
468
```
469
469
470
-
::: {.long-format}
470
+
::: {.narration}
471
471
There's a lot more you can do with `patchwork`, including adjusting the widths and heights, but we'll stop here for now.
472
472
:::
473
473
474
474
## Saving plots
475
475
476
-
::: {.long-format}
476
+
::: {.narration}
477
477
The last big thing you'll need to know about plotting is how to save your plots. `ggplot2` comes with a nifty `ggsave()` function which you can use to save your plots in a number of different formats. Here we'll save our most recent combined plot as both a PDF and a JPEG. The former is a vector format, meaning all of the elements of the figure as geometric shapes, and, because of this, none of the data is lost (aka "lossless"). The latter is a raster format, meaning the figure is converted to a 2-D array of colored pixels of a desired size, and because of this, some of the data is lost in the process (aka "lossy"). This results in the pixellation that you see when you zoom in on a JPEG. `ggsave()` detects what format you want based on the file extension, so we just need to specify the file location and the object to be saved (and optionally the dimensions of the output file). It's usually a good idea to keep all figures in their own folder (which was already created for you).
0 commit comments