-
Notifications
You must be signed in to change notification settings - Fork 15
/
14-Scales-and-guides.Rmd
341 lines (213 loc) · 14.3 KB
/
14-Scales-and-guides.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
# Scales and Guides
```{r 15-01, include=FALSE}
library(ggplot2)
```
**Learning objectives:**
* Illustrate that there is nothing preventing you from transforming other kinds of scales beyond continuous position scale
* Show how concepts for position scales apply elsewhere
* Discuss the theory underpinning scales and guides
## Theory of scales and guides
- Each scale is a function from a region in data space to a region in aesthetic space.
- The axis or legend is the inverse function, known as the **guide**: it allows you to convert visual properties back to data.
- Surprisingly, axes and legends are the same type of thing, but while they look very different they have the same purpose: to allow you to read observations from the plot and map them back to their original values.
The commonalities between the two are illustrated below:
|Argument name|Axis| Legend|
|-|-|-|
| `name` |Label| Title |
| `breaks` | Ticks & grid line|Key|
| `labels` |Tick label|Key label|
![](images/2023-10-13.png)
However, legends are more complicated than axes, and consequently there are a number of topics that are specific to legends:
**1.** A legend can display multiple aesthetics (e.g. colour and shape), from multiple layers (Section 15.7.1), and the symbol displayed in a legend varies based on the geom used in the layer (Section 15.8)
**2.** Axes always appear in the same place. Legends can appear in different places, so you need some global way of positioning them. (Section 11.7)
**3.** Legends have more details that can be tweaked: should they be displayed vertically or horizontally? How many columns? How big should the keys be? This is discussed in (Section 15.5)
### Scale specification
An important property of ggplot2 is the principle that every aesthetic in your plot is associated with exactly one scale. For instance, when you write this
```{r 15-02, echo=TRUE,eval=FALSE}
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = class))
```
ggplot2 adds a default scale for each aesthetic used in the plot:
```{r 15-03, echo=TRUE,eval=FALSE}
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = class)) +
scale_x_continuous() +
scale_y_continuous() +
scale_colour_discrete()
```
```{r 15-04, echo=TRUE,eval=FALSE}
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = class)) +
scale_x_continuous(name = "A really awesome x axis label") +
scale_y_continuous(name = "An amazingly great y axis label")
```
The use of `+` to “add” scales to a plot is a little misleading because if you supply two scales for the same aesthetic, the last scale takes precedence:
```{r 15-05, echo=TRUE,eval=FALSE}
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
scale_x_continuous(name = "Label 1") +
scale_x_continuous(name = "Label 2")
#> Scale for 'x' is already present. Adding another scale for 'x', which will
#> replace the existing scale.
ggplot(mpg, aes(displ, hwy)) +
geom_point() +
scale_x_continuous(name = "Label 2")
```
```{r 15-06, echo=TRUE,eval=FALSE}
ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = class)) +
scale_x_sqrt() +
scale_colour_brewer()
```
### Naming scheme
The scale functions intended for users all follow a common naming scheme. You’ve probably already figured out the scheme, but to be concrete, it’s made up of three pieces separated by "_":
**1.** `scale`
**2.** The name of the primary aesthetic (e.g., `colour`, `shape` or `x`)
**3.** The name of the scale (e.g., `continuous`, `discrete`, `brewer`).
### Fundamental scale types
All scale functions in ggplot2 belong to one of three fundamental types:
* continuous scales,
* discrete scales, and
* binned scales.
Each fundamental type is handled by one of three scale constructor functions:
* `continuous_scale()`,
* `discrete_scale()` and
* `binned_scale()`.
Although you should never need to call these constructor functions, they provide the organizing structure for scales and it is useful to know about them.
## Scale Breaks
Discussion of what unifies the concept of breaks across continuous, discrete and binned scales: they are specific data values at which the guide needs to display something. Include additional detail about break functions.
## Scale Limits
- Section 15.1 introduced the concept that a scale defines a mapping from the data space to the aesthetic space.
- Scale limits are an extension of this idea: they dictate the **region** of the data space over which the mapping is defined.
- For continuous and binned scales, the data space is inherently continuous and one-dimensional, so the limits can be specified by two end points.
- For discrete scales, however, the data space is unstructured and consists only of a set of categories: as such the limits for a discrete scale can only be specified by enumerating the set of categories over which the mapping is defined.
- The toolbox chapters outline the common practical goals for specifying the limits: for position scales the limits are used to set the end points of the axis, for example.
This leads naturally to the question of what ggplot2 should do if the data set contains “out of bounds” values that fall outside the limits.
- The default behaviour in ggplot2 is to convert out of bounds values to NA.
- We can override this default by setting `oob` argument of the scale, a function that is applied to all observations outside the scale limits.
- The default is `scales::oob_censor()` which replaces any value outside the limits with `NA`.
- Another option is `scales::oob_squish()` which squishes all values into the range. An example using a fill scale is shown below:
```{r 15-07}
df <- data.frame(x = 1:6, y = 8:13)
base <- ggplot(df, aes(x, y)) +
geom_col(aes(fill = x)) + # bar chart
geom_vline(xintercept = 3.5, colour = "red") # for visual clarity only
base
base + scale_fill_gradient(limits = c(1, 3))
base + scale_fill_gradient(limits = c(1, 3), oob = scales::squish)
```
The first plot the default fill colours are shown, ranging from dark blue to light blue.
In the second plot the scale limits for the fill aesthetic are reduced so that the values for the three rightmost bars are replace with NA and are mapped to a grey shade.
In some cases this is desired behaviour but often it is not: the third plot addresses this by modifying the `oob` function appropriately.
## Scale guides
Scale **guides** are more complex than **scale names**: where the `name` argument (and `labs()` ) takes text as input, the `guide` argument (and `guides()`) require a guide object created by a **guide function** such as `guide_colourbar()` and `guide_legend()`. These arguments to these functions offer additional fine control over the guide.
The table below summarises the default guide functions associated with different scale types:
|Scale type| Default guide type |
|-|-|
|continuous scales for colour / fill aesthetics | colourbar|
|binned scales for colour/fill aesthetics|coloursteps|
|position scales (continuous, binned, and discrete)| axis|
|discrete scales (except position scales)| legend|
|binned scalesd (except position/colour/fill scales)|bins|
Each of these guide types has appeared earlier in the toolbox:
* `guide_colourbar()` is discussed in Section 11.2.5
* `guide_coloursteps()` is discussed in Section 11.4.2
* `guide_axis()` is discussed in Section 10.3.2
* `guide_legend()` is discussed in Section 11.3.6
* `guide_bins()` is discussed in Section 12.1.2
In addition to the functionality discussed in those sections, the guide functions have many arguments that are equivalent to theme settings like text colour, size, font etc, but only apply to a single guide. For information about those settings, see Chapter 18.
## Scale transformation
The most common use for scale transformations is to adjust a continuous position scale, as discussed in Section 10.1.7. However, they can sometimes be helpful to when applied to other aesthetics. Often this is purely a matter of visual emphasis.
An example of this for the Old Faithful density plot is shown below. The linearly mapped scale on the left makes it easy to see the peaks of the distribution, whereas the transformed representation on the right makes it easier to see the regions of non-negligible density around those peaks:
```{r 15-08}
base <- ggplot(faithfuld, aes(waiting, eruptions)) +
geom_raster(aes(fill = density)) +
scale_x_continuous(NULL, NULL, expand = c(0, 0)) +
scale_y_continuous(NULL, NULL, expand = c(0, 0))
base
base + scale_fill_continuous(trans = "sqrt")
```
Transforming size aesthetics is also possible:
```{r 15-09}
df <- data.frame(x = runif(20), y = runif(20), z = sample(20))
base <- ggplot(df, aes(x, y, size = z)) + geom_point()
base
base + scale_size(trans = "reverse")
```
In the plot on the left, the `z` value is naturally interpreted as a “weight”: if each dot corresponds to a group, the `z` value might be the size of the group. In the plot on the right, the size scale is reversed, and `z` is more naturally interpreted as a “distance” measure: distant entities are scaled to appear smaller in the plot.
## Legend merging and splitting
There is always a one-to-one correspondence between position scales and axes. But the connection between non-position scales and legend is more complex: one legend may need to draw symbols from multiple layers (“merging”), or one aesthetic may need multiple legends (“splitting”).
### Merging legends
Merging legends occurs quite frequently when using ggplot2. For example, if you’ve mapped colour to both points and lines, the keys will show both points and lines. If you’ve mapped fill colour, you get a rectangle. Note the way the legend varies in the plots below:
By default, a layer will only appear if the corresponding aesthetic is mapped to a variable with `aes()`. You can override whether or not a layer appears in the legend with `show.legend: FALSE` to prevent a layer from ever appearing in the legend; `TRUE` forces it to appear when it otherwise wouldn’t. Using `TRUE` can be useful in conjunction with the following trick to make points stand out:
```{r 15-10, echo=FALSE}
toy <- data.frame(
const = 1,
up = 1:4,
txt = letters[1:4],
big = (1:4)*1000,
log = c(2, 5, 10, 2000)
)
```
```{r 15-11}
ggplot(toy, aes(up, up)) +
geom_point(size = 4, colour = "grey20") +
geom_point(aes(colour = txt), size = 2)
ggplot(toy, aes(up, up)) +
geom_point(size = 4, colour = "grey20", show.legend = TRUE) +
geom_point(aes(colour = txt), size = 2)
```
ggplot2 tries to use the fewest number of legends to accurately convey the aesthetics used in the plot. It does this by combining legends where the same variable is mapped to different aesthetics. The figure below shows how this works for points: if both colour and shape are mapped to the same variable, then only a single legend is necessary.
```{r 15-12}
base <- ggplot(toy, aes(const, up)) +
scale_x_continuous(NULL, breaks = NULL)
base + geom_point(aes(colour = txt))
base + geom_point(aes(shape = txt))
base + geom_point(aes(shape = txt, colour = txt))
```
In order for legends to be merged, they must have the same name. So if you change the name of one of the scales, you’ll need to change it for all of them. One way to do this is by using `labs()` helper function:
```{r 15-13}
base <- ggplot(toy, aes(const, up)) +
geom_point(aes(shape = txt, colour = txt)) +
scale_x_continuous(NULL, breaks = NULL)
base
base + labs(shape = "Split legend")
base + labs(shape = "Merged legend", colour = "Merged legend")
```
### Splitting legends
Splitting a legend is a much less common data visualization task. In general it is not advisable to map one aesthetic (e.g. colour) to multiple variables, and so by default ggplot2 does not allow you to “split” the colour aesthetic into multiple scales with separate legends.
Nevertheless, there are exceptions to this general rule, and it is possible to override this behaviour using the ggnewscale package. The `ggnewscale::new_scale_colour()` command acts as an instruction to ggplot2 to initialize a new colour scale: scale and guide commands that appear above the `new_scale_colour()` command will be applied to the first colour scale, and commands that appear below are applied to the second colour scale.
To illustrate this the plot on the left uses `geom_point()` to display a large marker for each vehicle make in the mpg data, with a single colour scale that maps to the year. On the right, a second `geom_point()` layer is overlaid on the plot using small markers: this layer is associated with a different colour scale, used to indicate whether the vehicle has a 4-cylinder engine.
```{r 15-14}
base <- ggplot(mpg, aes(displ, hwy)) +
geom_point(aes(colour = factor(year)), size = 5) +
scale_colour_brewer("year", type = "qual", palette = 5)
base
base +
ggnewscale::new_scale_colour() +
geom_point(aes(colour = cyl == 4), size = 1, fill = NA) +
scale_colour_manual("4 cylinder", values = c("grey60", "black"))
```
Additional details, including functions that apply to other scale types, are available on the package website, https://github.com/eliocamp/ggnewscale.
## Legend key glyphs
In most cases the default glyphs shown in the legend key will be appropriate to the layer and the aesthetic. Should you need to override this behaviour, the `key_glyph` argument can be used to associate a particular layer with a different kind of glyph. For example:
```{r 15-15}
base <- ggplot(economics, aes(date, psavert, color = "savings"))
base + geom_line()
base + geom_line(key_glyph = "timeseries")
```
More precisely, each geom is associated with a function such as `draw_key_path()`, `draw_key_boxplot()` or `draw_key_path()` which is responsible for drawing the key when the legend is created. You can pass the desired key drawing function directly: for example, `base + geom_line(key_glyph = draw_key_timeseries)` would also produce the plot shown above.
For more information about changing key glyphs, see https://www.emilhvitfeldt.com/post/changing-glyph-in-ggplot2/.
## Meeting Videos
### Cohort 1
`r knitr::include_url("https://www.youtube.com/embed/8fjjoGTGC6c")`
<details>
<summary> Meeting chat log </summary>
```
00:07:09 June Choe: hello!
00:08:55 Federica Gazzelloni: Hello!
00:46:16 Kent Johnson: Examples of key glyphs: https://www.emilhvitfeldt.com/post/changing-glyph-in-ggplot2/
00:48:30 June Choe: that one is just two overlapping points i think (with different sizes)
00:48:35 June Choe: (yes what kent said)
```
</details>