-
Notifications
You must be signed in to change notification settings - Fork 15
/
viz.qmd
527 lines (379 loc) · 16.7 KB
/
viz.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
---
title: "Vizualization with ggplot2"
date-modified: 'today'
date-format: long
license: CC BY-NC
bibliography: references.bib
---
I only need the `ggplot2` [package](packages.html) but I like to load `tidyverse` because it includes 8 complimentary packages, including `ggplot2`.
```{r}
#| message: false
#| warning: false
# library(ggplot2)
library(tidyverse)
```
Get more information from:
- https://tidyverse.org
- https://ggplot2.tidyverse.org
## ggplot2 template code
The ggplot2 template is used to identify the dataframe, identify the x and y axis, and define visualized layers
> `ggplot(data = ---, mapping = aes(x = ---, y = ---)) + geom_----()`
Note: `----` is meant to imply text you supply. e.g. function names, data frame names, variable names.
It is helpful to see the argument mapping, above. In practice, rather than typing the formal arguments, code is typically shorthanded to this:
> `dataframe |> ggplot(aes(xvar, yvar)) + geom_----()`
## Goal
Visualize a scatter plot showing the relationship of mass to height for *Star Wars* characters in the `dplyr::starwars` dataframe, excluding the heaviest character. Indicate a linear regression line.
```{r}
#| message: false
#| warning: false
#| echo: false
starwars %>%
filter(mass < 500) %>%
ggplot(aes(height, mass)) +
geom_point() +
geom_smooth(method = lm, se = FALSE)
```
## Import data
dplyr has an on-board dataset, `starwars`
```{r}
data(starwars)
starwars
```
## Steps to Visualization
### Draw the base layer
This feels like, and looks like, you drew an empty box. This is the foundation canvas layer for the resulting visualization.
::: column-margin
```{=html}
<iframe width="300" height="200" src="https://www.youtube.com/embed/TIJzx5eQbgk" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
```
:::
```{r}
starwars %>%
ggplot()
```
### Map the aesthetics to variables in the data frame
Still doesn't look like much. {ggplot2} will initialize the plot scales and labels based on the values of the variables in the data frame.
```{r}
starwars %>%
filter(mass < 500) %>%
ggplot(aes(height, mass))
```
In the above, I subset the data, removing any *Star Wars* characters weighing more than 500 Kg -- `dplyr::filter()`. Then I initialized the base layer and map the x-axis to `height`, and the y-axis to `mass`. ggplot drew the scales for me.
### Visualize a layer
Since I have two numeric variables, `height` and `mass`, I'll start with a scatter plot. Scatter plots are generated by the `geom_point()` function.
```{r}
#| message: false
#| warning: false
starwars %>%
filter(mass < 500) %>%
ggplot(aes(height, mass)) +
geom_point()
```
### Global v local arguments
So far, the **aesthetics** are **mapped** in the `aes()` function within the initial `ggplot` function. As such, these values are mapped globally and all layers are affected by this mapping. See the `aes()` function, above. Arguments can also be mapped locally, within a geom function layer, as as `geom_point(aes(height, mass))`.
```{r}
#| message: false
#| warning: false
starwars %>%
filter(mass < 500) %>%
ggplot() +
geom_point(aes(height, mass))
```
### Mapping v Setting
Dataframe values can be *mapped* inside the aesthetic, `aes()`, to visualize variable dataframe values. Alternatively, data values can be *set* as an argument outside the `aes()` function but inside the geom\_ function. This is done to affect a visual quality that is manually assigned, as opposed to being derived from variable data values.
Aesthetic arguments include:
- color
- fill
- size
- linetype
- opacity
- shape
- *and more.* See [documentation for each geom\_ layer](https://ggplot2.tidyverse.org/reference/index.html#layers).
> Mapping: `color` is **mapped** *inside* `aes()` function. In this case, `color = starwars$gender`
```{r}
#| message: false
#| warning: false
starwars %>%
filter(mass < 500) %>%
ggplot() +
# geom_point(mapping = aes(x = height, y = mass, color = gender))
geom_point(aes(height, mass, color = gender))
```
Notice the legend was drawn automatically, above, by mapping an aesthetic
> Setting: The `color` argument can be **set** outside the `aes()` function, but within the `geom_` function. In this case with `color = "goldenrod"`
```{r}
#| message: false
#| warning: false
starwars %>%
filter(mass < 500) %>%
ggplot() +
geom_point(aes(height, mass), color = "goldenrod")
```
## Layers
::: callout-tip
## More layers
A list of all available `geom_` functions, or **layers**, can be found in the help or on the [ggplot2 website](https://ggplot2.tidyverse.org/reference/index.html#section-geoms "ggplot2 layers")
:::
### Common `geom_` functions
| Type | Geom |
|------------------|----------------------------------|
| Bar graph: | `geom_bar()` `geom_col()` |
| Histogram: | `geom_histogram()` |
| Scatter plot: | `geom_point()` `geom_jitter()` |
| Line graph: | `geom_line()` |
| Box plot: | `geom_boxplot()` |
| Density: | `geom_density()` `geom_violin()` |
| Heat map: | `geom_heatmap()` |
| Mapping: | `geom_sf()` |
| Regression line: | `geom_smooth()` |
### Boxplot
```{r}
#| message: false
#| warning: false
starwars %>%
mutate(species = fct_lump_min(species, 2)) %>%
ggplot(aes(species, height)) +
geom_boxplot()
```
### Line graph
```{r}
#| message: false
#| warning: false
babynames::babynames %>%
filter(name == "Watts") %>%
ggplot(aes(year, n)) +
# geom_point() +
geom_line()
```
### Overplotting
There are two simple approaches to visualizing overplotted data: `geom_jitter()` and decrease the opacity be setting the `alpha =` argument.
- Adjust **opacity**. The `alpha` argument within the geom function affects the opacity of the points. In this way, overplotted data will appear as darker points on the plot
```{r}
starwars %>%
filter(mass < 500) %>%
ggplot() +
geom_point(aes(height, mass), alpha = .3)
```
- **Jitter** the data with `geom_jitter()`
`geom_jitter` will not change the values of the data but it will offset data points, making it easier to perceive the overplotting.
```{r}
starwars %>%
filter(mass < 500) %>%
ggplot() +
geom_jitter(aes(height, mass))
```
### Multiple layers
Each layer, visualized by a geom\_ function, can support local arguments and draw from the global settings. Below we use the `geom_line()` function, followed by the `geom_point()` function.
```{r}}
# simplified code
babynames %>%
ggplot(aes(year, prop)) +
geom_line(aes(color = sex)) +
geom_point(alpha = 0.4, shape = "cross")
```
```{r}
#| warning: false
#| message: false
#| code-fold: true
#| code-summary: "Show the full code"
library(babynames)
library(ggplot2)
babynames %>%
filter(name == "John" & sex == "M" |
name == "Elizabeth" & sex == "F") %>%
ggplot(aes(year, prop)) +
geom_line(aes(color = sex)) +
geom_point(alpha = 0.4, shape = "cross") +
geom_text(data = . %>% filter(year == 1965), aes(label = name),
nudge_y = .009) +
labs(title = "Name Popularity") +
theme(legend.position = "none")
```
### Goal
Recall the goal mentioned in the beginning. We want a scatter plot and a regression line. The regression line is drawn with the `geom_smooth()` function.
```{r}
#| message: false
#| warning: false
starwars %>%
filter(mass < 500) %>%
ggplot(aes(height, mass)) +
geom_point() +
geom_smooth(method = lm, se = FALSE)
```
## Arrange order
Categorical values are ordered with the `forcats` library. Part of the Tidyverse, the [forcats](https://forcats.tidyverse.org/) package is used to transform string data into the factor data-type. For example, eye colors can be categorized. Brown, blue, and green are nominal categorical values for the factor variable `eye_color`. Among other things, treating `eye_color` as a factor data type enables visual ordering of categorical values by frequency.
#### Before arranging order
```{r}
msleep %>%
ggplot(aes(vore)) +
geom_bar()
```
### Arranging order with {forcats}
Change the order of the bars by the frequency of observations using `forcats::fct_infreq()`
```{r}
msleep %>%
ggplot(aes(fct_infreq(vore))) +
geom_bar()
```
Notice below, we use the `fill =` argument to set the color of an individual bar. In the scatter plot examples, above, we used the `color =` argument. In many `geoms_` you can use both `color` and `fill` arguments. How do these arguments differ? Where can you look to find out more about `fill` and `color`?[^1]
[^1]: The documentation for each layer. You can find documentation at [https://ggplot2.tidyverse.org](https://ggplot2.tidyverse.orghttps://ggplot2.tidyverse.org) or in the RStudio IDE by looking in the Files Quadrant \> the Help tab.
```{r}
starwars %>%
ggplot(aes(fct_rev(fct_infreq(eye_color)))) +
geom_bar(fill = "grey70") +
geom_bar(data = starwars %>% filter(eye_color == "orange"), fill = "darkorange") +
coord_flip()
```
## Facet wrap
Faceting is great way to make subplots of the same data frame. See both `facet_wrap()` and `facet_grid()`
```{r}
mpg %>%
ggplot(aes(displ, hwy)) +
geom_point() +
facet_wrap(vars(class))
```
## Scales
Scales are used to affect the visual qualities of the data. Scales help visualize discrete categories by associating each discrete value with a specific color. [Read more about scales](https://ggplot2.tidyverse.org/reference/index.html#section-scales).
Viridis scales apply color palettes to continuous, discrete, or binned data. For discrete data we can use the `scale_fill_viridis_d()` function.
> By using one the `scale_fill_` functions, we are able to affect the variable values associated in the `fill = conservation` argument.
```{r}
my_plot <- msleep %>%
ggplot(aes(fct_infreq(vore), sleep_total)) +
geom_col(aes(fill = conservation))
my_plot +
scale_fill_viridis_d(na.value = "grey80")
```
The color brewer palette is similar but has a wider array of palettes to choose from. Below we use `scale_fill_brewer()` and a default *qualitative* color palette by setting the `type =` argument to *qual* (for qualitative). Alternatively, or additionally, we could assign a `palette =` argument to choose a particular ColorBrewer palette, such as choosing the "Dark2" palette with the argument `palette = "Dark2"`
```{r}
my_plot +
scale_fill_brewer(type = "qual", na.value = "grey80")
```
Sometimes a manual scale is preferred. Below we use `scale_fill_manual()` to associate a defined set of color names with my `fill = conservation` argument
```{r}
mycolors <- c("firebrick", "forestgreen", "navy", "darkorange",
"goldenrod", "sienna")
my_plot +
scale_fill_manual(values = mycolors, na.value = "grey80")
```
To find available colors: Google search "R color names", or specific to ColorBrewer....
```{r}
#| fig-height: 8
#display.brewer.pal(7,"Dark2")
RColorBrewer::display.brewer.all()
```
Scales are used to manipulate the visual properties of the data. Beyond using scales to modify colors, another example is logarithmic scales to account for data skew. In this way you can clarify the data pattern. For example, using the `ChickWeight` dataset, we visualize the weights of the chicks over time. Hint: You can visualize the data skew with a histogram, `geom_histogram()`.
```{r}
data("ChickWeight")
ChickWeight %>%
ggplot(aes(Time, weight, color = Diet)) +
geom_line(aes(group = Chick))
```
Using `scale_y_log10` we can alter the scale to highlight a more understandable data pattern
```{r}
chicken_plot <- ChickWeight %>%
ggplot(aes(Time, weight, color = Diet)) +
geom_line(aes(group = Chick)) +
scale_y_log10()
chicken_plot
```
## Labels
The `labs()` function is a specialized scales function, used to apply labels. For example, use the `labs()` function to add a title, subtitle, legend title, modify axis labels, and set a caption. See more on [scales](https://ggplot2.tidyverse.org/reference/index.html#section-scales).
First let's wrangle a data frame, make a plot, and assign it to an object name
```{r}
#| label: msleep-prep
#| message: false
#| warning: false
plot_sleep <- msleep %>%
mutate(vore = case_when(
vore == "herbi" ~ "Herbivore",
vore == "omni" ~ "Omnivore",
vore == "carni" ~ "Carnivore",
vore == "insecti" ~ "Insectivore"
)) %>%
mutate(my_order = sum(sleep_total), .by = vore) |>
summarise(sleep_total = sum(sleep_total, na.rm = TRUE), .by = c(vore, my_order, conservation)) |>
ggplot(aes(fct_rev(fct_reorder(vore, my_order)), sleep_total)) +
geom_col(aes(fill = conservation)) +
scale_fill_brewer(type = "qual", na.value = "grey80")
```
Now we can add labels with the `labs` function
```{r}
#| label: plot-sleep-labs
plot_sleep +
labs(title = "Animal sleep times",
subtitle = "A practice dataset",
fill = "Conservation\nType",
x = "",
y = "Sleep time in hours",
caption = "Source: ggplot::msleep")
```
## Themes
Themes are used to manipulate the stylistic characteristics of the non-data components of your plot, such as font faces, text sizes, and grid lines. **ProTip:** quickly manipulate a single plot with preset themes such as `theme_dark`, or use a specialized theme extension such as `theme_ipsum` from the `hrbrthemes` package.
- https://ggplot2.tidyverse.org/reference/ggtheme.html
- for example... `theme_dark()`, `theme_light()`, `theme_classic()`
- https://cinc.rud.is/web/packages/hrbrthemes/
- https://yutannihilation.github.io/allYourFigureAreBelongToUs/ggthemes/
See more on [themes](https://ggplot2.tidyverse.org/reference/index.html#section-themes)
### Example themes
![Image source: from R for Data Science by Grolemund & Wickham](https://r4ds.had.co.nz/images/visualization-themes.png){height="6in"}
### theme_dark()
```{r}
plot_sleep +
theme_dark()
```
### theme_classic
```{r}
plot_sleep +
theme_classic()
```
### hbrthemes
https://cinc.rud.is/web/packages/hrbrthemes/
```{r}
#| message: false
#| warning: false
plot_sleep +
hrbrthemes::theme_ipsum(grid = "Y") +
hrbrthemes::scale_fill_ipsum(na.value = "grey80",
labels = c("Critical", "Domesticated",
"Endangered", "Least Concern",
"Threatened", "Vulnerable")) +
theme(plot.title.position = "plot")
```
## Combine plots
The `patchwork` package makes it "ridiculously simple to combine separate ggplot objects into the same graphic." The `/`will separate plots vertically. The `|` will separate plots horizontally. See more about [patchwork](https://patchwork.data-imaginist.com/)
> Try also: (plot_sleep \| chicken_plot)
```{r}
#| label: patchwork-example
# https://patchwork.data-imaginist.com/
library(patchwork)
(plot_sleep / chicken_plot)
```
## Interactive plots
Use the `ggplotly` function will transform your static ggplot object into an interactive plot for use in dashboards and web presentations. ggplotly[^2] is an example of [HTML widgets for R](https://htmlwidgets.org)[^3], an easy to implement approach that will be explained more in the [next section](widgets.html).
[^2]: See Also: the [Plotly ggplot2 Library](https://plotly.com/ggplot2/) page, and the [*Interactive web-based data visualization with R, plotly, and shiny*](https://plotly-r.com/) book.
[^3]: HTML widgets use JavaScript visualization libraries just by using the R language. The widgets can be embedded into Quarto and R Markdown documents.
<!-- Requires an older version of {knitr} -->
<!-- remotes::install_version("knitr", version = "1.42") -->
```{r}
#| label: plotly-example
#| message: false
#| warning: false
library(plotly)
ggplotly(plot_sleep)
```
For more advanced interactivity we'll also explore [ObservableJS](interactive.html).[^4]
[^4]: Through Quarto you can leverage [ObservableJS](https://observablehq.com/@observablehq/observables-not-javascript), an especially interactive application that is perfect for end-user interactive data exploration.
## Animate plots
Use the {`gganimate`} package to bring your plot to life through the wonders of animation. Learn more at the resource page for [gganimate](https://gganimate.com/)
For Example:
```{r}
#| label: example-gganimate
#| echo: false
#| message: false
#| warning: false
library(htmltools)
img(src = knitr::include_graphics("images/gganmimate_example.gif"), alt = 'gganmimate example')
div(class="captxt", "Image source: https://gganimate.com/index.html#yet-another-example")
```
## Attribution
Adapted in whole or in part; based on the [Visualize Data with ggplot2](https://github.com/rstudio/master-the-tidyverse/blob/master/pdfs/01-Visualize-Data.pdf) slides by Garrett Grolemund at RStudio which carries the CC BY Garrett Grolemund, RStudio license.