-
Notifications
You must be signed in to change notification settings - Fork 15
/
20-Extending-ggplot2.Rmd
265 lines (175 loc) · 6.33 KB
/
20-Extending-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
# Extending ggplot2
**Learning objectives:**
- How to overcome the challenge of a particular plot
- Learn how to extend ggplot2 in different ways
---
## Overview
In this chapter we see how to extend the graphics of a plot, in particular we will see how the following layers and other key part of a plot are composed, and where the changes can be applied.
- Themes
- Stats
- Geoms
- Coords
- Scales
- Positions
- Facets
- Guides
---
```{r 21-01,message=FALSE, warning=FALSE, include=FALSE, paged.print=FALSE}
library(tidyverse)
library(patchwork)
```
## Themes
**How about creating new theme elements?**
The base is theme is `theme_grey()`, then here is an example of the modification made on `theme_bw()` to obtain `theme_minimal()`.
The `theme_*` is the easiest part of a plot to be modified.
Use the `print()` function on a theme_<...> to see its specifications, the `%+replace%` operator shows where the substitutions have taken place.
print(theme_grey)
print(theme_minimal) and %+replace% operator
```{r 21-02,echo=FALSE}
df<-data.frame(x=seq(1,10,1),y=rnorm(100))
tg<-ggplot(data=df,aes(x,y))+
geom_blank()+
labs(title="Theme grey") +
theme_grey()
bw<-ggplot(data=df,aes(x,y))+
geom_blank()+
labs(title="Theme bw") +
theme_bw()
tm<- ggplot(data=df,aes(x,y))+
geom_blank()+
labs(title="Theme minimal") +
theme_minimal()
tg|bw|tm
```
```{r 21-03}
print(theme_bw)
```
```{r 21-04}
print(theme_minimal)
```
While if we call the function: `print(theme_minimal())`, we can see all the options set available.
In general, if you want to make a modification to an existing theme, the general approach is to simply use the `theme()` function while setting `complete = TRUE`.
---
## Stats
> Extending stats is one of the most useful ways to extend the capabilities of ggplot2
> Stats are purely about data transformations
Creating new stats *stat* with these extension functions:
- `compute_*()`
- `setup_*()`
The logic of a **stat** is made of subsequent calls:
```{r 21-05,echo=FALSE, fig.align='center', fig.dim="100%"}
DiagrammeR::mermaid("
graph LR
A(compute_layer)-->B(compute_panel)
B-->C(compute_group)
",height = '100%', width = '100%')
```
```{r 21-06,echo=FALSE, fig.align='center', fig.dim="100%"}
DiagrammeR::mermaid("
graph TB
A(compute_layer)---B(split the data by the PANEL column)
B---C(call compute_panel)
C---D(reassemble the results)
E(compute_panel)---F(split the panel data by the group column)
F---G(call compute_group)
G---H(reassemble the results)
I(compute_group)---L(group transformation)
",height = '100%', width = '100%')
```
In general the transformation is done to single group starting at the `compute_group()` level.
Before `compute_*()` calls are the`setup_*()` functions which allows the Stat to react and modify itself in response to the given parameters.
```{r 21-07,echo=FALSE, fig.align='center', fig.dim="100%"}
DiagrammeR::mermaid("
graph TB
A(setup_params)-->B(receives the parameters input)
B-->C(returns a modified list of parameters)
D(setup_data)-->E(receives the modified parameters)
E-->F( returns the modified layer data)
",height = '100%', width = '100%')
```
>Sometimes, with related stats, all that is necessary is to make a subclass and provide new setup_params()/setup_data() methods.
```{r 21-08}
print(stat_bin())
```
## Geoms
**Why making a new geom_?**
- not meaningful data by any current geoms
- combination of the output of multiple geoms
- needs for grobs not currently available from existing geoms.
The logic of a **geom** is made of subsequent calls:
```{r 21-09,echo=FALSE, fig.align='center', fig.dim="100%"}
DiagrammeR::mermaid("
graph LR
A(draw_layer)-->B(draw_panel)
B-->C(draw_group)",height = '100%', width = '100%')
```
Implementation is easier for `draw_group()`
- `setup_params()+setup_data()`
- overwriting the `setup_data()`
**Example**
Reparameterisation of `geom_segment()` with `geom_spoke()`
```{r 21-10}
print(GeomSpoke$setup_data)
```
**Example**
`geom_smooth()` as a combination of `geom_line()` and `geom_ribbon()`
- preparing the data for each of the geoms inside the `draw_*()`
```{r 21-11}
print(GeomSmooth$draw_group)
```
## Coords
**Example:**
CoordCartesian rescaling the position data
Coords takes care of rendering the axes, axis labels, and panel foreground and background and it can intercept both the layer data and facet layout and modify it, with:
- `draw_*()`
- `transform()`
**Example**
```{r 21-12}
print(CoordCartesian$transform)
```
```{r 21-13,eval=FALSE, include=T}
print(coord_sf)
```
## Scales
**Example**
Build a wrapper for a new palette to an existing scale.
This is done by providing a new palette scale into the relevant basic scale.
```{r 21-14}
print(scale_fill_viridis_c)
```
## Other important parts
### Positions
The Position class is slightly simpler than the other ggproto classes.
```{r 21-15,echo=FALSE, fig.align='center', fig.dim="100%"}
DiagrammeR::mermaid("
graph LR
A(compute_layer)-->B(compute_panel)
C(setup_params)-->D(setup_data)
",height = '100%', width = '100%')
```
### Facets
Look at **FacetWrap** or **FacetGrid**, and simply provide new `compute_layout()`, and `map_data()` methods
### Guides
What is a `ggproto`?
The answer is back in chapter20 [ggplot2 internals](https://ggplot2-book.org/internals.html)
---
## References
[Extending ggplot2](https://ggplot2.tidyverse.org/articles/extending-ggplot2.html)
[A List of ggplot2 extensions](https://exts.ggplot2.tidyverse.org/)
[ggplot Extension Course](https://mq-software-carpentry.github.io/r-ggplot-extension/aio.html)
---
## Meeting Videos
### Cohort 1
`r knitr::include_url("https://www.youtube.com/embed/mPAvK6EzbiQ")`
<details>
<summary> Meeting chat log </summary>
```
00:10:52 June Choe: I'm fine with anything!
00:39:47 Federica Gazzelloni: - [Extending ggplot2](https://ggplot2.tidyverse.org/articles/extending-ggplot2.html)
- [A List of ggplot2 extensions](https://exts.ggplot2.tidyverse.org/)
- [ggplot Extension Course](https://mq-software-carpentry.github.io/r-ggplot-extension/aio.html)
- [Example](https://github.com/EvaMaeRey/mytidytuesday/blob/master/2022-01-03-easy-geom-recipes/easy_geom_recipes.Rmd)
- [extending-your-ability-to-extend-ggplot2](https://www.rstudio.com/resources/rstudioconf-2020/extending-your-ability-to-extend-ggplot2/)
- [ggtrace](https://yjunechoe.github.io/ggtrace-user2022/#/title-slide)
```
</details>