forked from YuLab-SMU/treedata-book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path06_ggtree_manipulation.Rmd
359 lines (235 loc) · 15.3 KB
/
06_ggtree_manipulation.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
# Visual Exploration of Phylogenetic Tree {#chapter6}
```{r include=FALSE}
library("ape")
library("ggplot2")
library("cowplot")
library("ggtree")
expand <- ggtree::expand
rotate <- ggtree::rotate
flip <- ggtree::flip
```
The `r Biocpkg("ggtree")` [@yu_ggtree:_2017] supports many ways of manipulating the tree visually, including viewing selected clade to explore large tree (Figure \@ref(fig:viewClade)), taxa clustering (Figure \@ref(fig:groupOTU)), rotating clade or tree (Figure \@ref(fig:rfClade)B and \@ref(fig:rotateTree)), zoom out or collapsing clades (Figure \@ref(fig:collapseExpand)A and \@ref(fig:scaleClade)), *etc.*. Details tree manipulation functions are summarized in Table \@ref(tab:treeman).
```{r treeman, echo=FALSE, out.extra='', message=FALSE}
treeman <- matrix(c(
"collapse", "collapse a selecting clade",
"expand", "expand collapsed clade",
"flip", "exchange position of 2 clades that share a parent node",
"groupClade", "grouping clades",
"groupOTU", "grouping OTUs by tracing back to most recent common ancestor",
"identify", "interactive tree manipulation",
"rotate", "rotating a selected clade by 180 degree",
"rotate_tree", "rotating circular layout tree by specific angle",
"scaleClade", "zoom in or zoom out selecting clade",
"open_tree", "convert a tree to fan layout by specific open angle"
), ncol=2, byrow=TRUE)
treeman <- as.data.frame(treeman)
colnames(treeman) <- c("Function", "Descriptiotn")
knitr::kable(treeman, caption = "Tree manipulation functions.", booktabs = T) %>%
kable_styling(latex_options = c("striped", "hold_position"), full_width = T)
```
## Viewing Selected Clade
A clade is a monophyletic group that contains a single ancestor and all of its descendants. We can visualize a specific selected clade via the `viewClade` function as demonstrated in Figure \@ref(fig:viewClade)B. Another solution is to extract the selected clade as a new tree object as described in [session 2.5](#subsetting-tree-with-data). These functions are developed to help users exploring large tree.
(ref:viewCladescap) Viewing a selected clade of a tree.
(ref:viewCladecap) **Viewing a selected clade of a tree.** An example tree used to demonstrate how *ggtree* support exploring or manipulating phylogenetic tree visually (A). The *ggtree* supports visualizing selected clade (B). A clade can be selected by specifying a node number or determined by most recent common ancestor of selected tips.
\setstretch{1.2}
```{r eval=F, fig.cap="(ref:viewCladecap)", fig.scap="(ref:viewCladescap)", out.extra=''}
library(ggtree)
nwk <- system.file("extdata", "sample.nwk", package="treeio")
tree <- read.tree(nwk)
p <- ggtree(tree) + geom_tiplab()
viewClade(p, MRCA(p, "I", "L"))
```
\setstretch{1.5}
```{r viewClade, echo=F, fig.cap="(ref:viewCladecap)", message=F, warning=F, fig.scap="(ref:viewCladescap)", out.extra='', out.width='100%'}
library(ggtree)
nwk <- system.file("extdata", "sample.nwk", package="treeio")
tree <- read.tree(nwk)
p <- ggtree(tree) + geom_tiplab()
p2 <- viewClade(p, MRCA(p, "I", "L"))
library(cowplot)
plot_grid(p, p2, ncol=2, labels = c("A", "B"))
```
Some of the functions, *e.g.* `viewClade`, work with clade and accept a parameter of internal node number. To get the internal node number, user can use `MRCA()` function (as in Figure \@ref(fig:viewClade)) by providing two taxa names. The function will return node number of input taxa's most recent common ancestor (MRCA). It works with tree and graphic (*i.e.* `ggtree()` output) object. `r CRANpkg("tidytree")` also provide `MRCA` function to extract information of MRCA node (see details in [session 2.1.3](#accesor-tidytree)).
## Scaling Selected Clade {#scale-clade}
The *ggtree* provides another option to zoom out (or compress) these clades via the `scaleClade` function. In this way, we retain the topology and branch lengths of compressed clades. This helps to save the space to highlight those clades of primary interest to the study.
(ref:scaleCladescap) Scaling selected clade.
(ref:scaleCladecap) **Scaling selected clade.** Clades can be zoom in (if `scale > 1`) to highlight or zoom out to save space.
\setstretch{1.2}
```{r scaleClade, message=FALSE, fig.cap="(ref:scaleCladecap)", fig.scap="(ref:scaleCladescap)", out.extra='', out.width='100%'}
tree2 <- groupClade(tree, c(17, 21))
p <- ggtree(tree2, aes(color=group)) + theme(legend.position='none') +
scale_color_manual(values=c("black", "firebrick", "steelblue"))
scaleClade(p, node=17, scale=.1)
```
\setstretch{1.5}
If users want to emphasize important clades, they can use `scaleClade` function with `scale` parameter larger than 1. Then the selected clade will be zoomed in. Users can also use `groupClade` to select clades and color them with different colors as shown in Figure \@ref(fig:scaleClade).
## Collapsing and Expanding Clade
It is a common practice to prune or collapse clades so that certain aspects of a tree can be emphasized. The *ggtree* supports collapsing selected clades using the `collapse` function as shown in Figure \@ref(fig:collapseExpand)A.
(ref:collapseExpandscap) Collapsing selected clades and expanding collapsed clades.
(ref:collapseExpandcap) **Collapsing selected clades and expanding collapsed clades.** Clades can be selected to collapse (A) and the collapsed clades can be expanded back (B) if necessary as *ggtree* stored all information of species relationships. Green and red symbols were displayed on the tree to indicate the collapsed clades.
\setstretch{1.2}
```{r collapseClade, eval=F, fig.cap="(ref:collapseCladecap)", fig.scap="(ref:collapseCladescap)", out.extra=''}
p2 <- p %>% collapse(node=21) +
geom_point2(aes(subset=(node==21)), shape=21, size=5, fill='green')
p2 <- collapse(p2, node=23) +
geom_point2(aes(subset=(node==23)), shape=23, size=5, fill='red')
print(p2)
expand(p2, node=23) %>% expand(node=21)
```
\setstretch{1.5}
```{r collapseExpand, echo=F, fig.cap="(ref:collapseExpandcap)", fig.scap="(ref:collapseExpandscap)", out.extra='', fig.width=8, fig.height=4, out.width='100%'}
p2 <- p %>% collapse(node=21) +
geom_point2(aes(subset=(node==21)), shape=21, size=5, fill='green')
p2 <- collapse(p2, node=23) +
geom_point2(aes(subset=(node==23)), shape=23, size=5, fill='red')
p3 <- expand(p2, node=23) %>% expand(node=21)
plot_grid(p2, p3, ncol=2, labels=c("A", "B"))
```
Here two clades were collapsed and labelled by green circle and red square symbolic points. Collapsing is a common strategy to collapse clades that are too large for displaying in full or are not primary interest of the study. In *ggtree*, we can expand (*i.e.*, uncollapse) the collapsed branches back with `expand` function to show details of species relationships as demonstrated in Figure \@ref(fig:collapseExpand)B.
Triangles are often used to represent the collapsed clade and `r Biocpkg("ggtree")` also supports it. The `collapse` function provides a "mode" parameter, which by default is "none" and the selected clade was collapsed as a "tip". User can specify `mode` to "max" (Figure \@ref(fig:collapseMode)A), "min" (Figure \@ref(fig:collapseMode)B) and "mixed" (Figure \@ref(fig:collapseMode)C).
```r
p2 <- p + geom_tiplab()
node <- 21
collapse(p2, node, 'max') %>% expand(node)
collapse(p2, node, 'min') %>% expand(node)
collapse(p2, node, 'mixed') %>% expand(node)
```
We can pass additional parameter to set the color and transparency of the triangles (Figure \@ref(fig:collapseMode)D).
```r
collapse(p, 21, 'mixed', fill='steelblue', alpha=.4) %>%
collapse(23, 'mixed', fill='firebrick', color='blue')
```
We can combine [scaleClade](#scale-clade) with `collapse` to zoom in/out of the triangles (Figure \@ref(fig:collapseMode)E).
```r
scaleClade(p, 23, .2) %>% collapse(23, 'min', fill="darkgreen")
```
(ref:collapseModescap) Collapse clade as triangle.
(ref:collapseModecap) **Collapse clade as triangle.** 'max' takes the position of most distant tip (A). 'min' takes the position of closest tip (B). 'mixed' takes the positions of both closest and distant tips (C), which looks more like the shape of the clade. Set color, fill and alpha of the triangles (D). Combine with `scaleClade` to zoom out triangle to save space (E).
```{r collapseMode, echo=F, fig.width=8, fig.height=8, fig.cap="(ref:collapseModecap)", fig.scap="(ref:collapseModescap)", out.width='100%'}
p2 <- p + geom_tiplab()
node <- 21
g1 = expand(collapse(p2, node, 'max'), node)
g2 = expand(collapse(p2, node, 'min'), node)
g3 = expand(collapse(p2, node, 'mixed'), node)
pp = plot_grid(g1,g2,g3, ncol=3, labels=LETTERS[1:3])
pg1 <- collapse(p, 21, 'mixed', fill='steelblue', alpha=.4) %>%
collapse(23, 'mixed', fill='firebrick', color='blue')
pg2 <- scaleClade(p, 23, .2) %>% collapse(23, 'min', fill="darkgreen")
gg <- plot_grid(pg1, pg2, ncol=2, labels=LETTERS[4:5])
plot_grid(pp, gg, ncol=1)
```
## Grouping Taxa {#group-taxa-vis}
The `groupClade` function assigns the branches and nodes under different clades into different groups. _`groupClade`_ accepts an internal node or a vector of internal nodes to cluster clade/clades.
Similarly, `groupOTU` function assigns branches and nodes to different groups based on user-specified groups of operational taxonomic units (OTUs) that are not necessarily within a clade, but can be monophyletic (clade), polyphyletic or paraphyletic. It accepts a vector of OTUs (taxa name) or a list of OTUs and will trace back from OTUs to their most recent common ancestor (MRCA) and cluster them together as demonstrated in Figure \@ref(fig:groupOTU).
A phylogenetic tree can be annotated by mapping different line type, size, color or shape to the branches or nodes that have been assigned to different groups.
(ref:groupOTUscap) Grouping OTUs.
(ref:groupOTUcap) **Grouping OTUs.** OTU clustering based on their relationships. Selected OTUs and their ancestors upto MRCA will be clustered together.
\setstretch{1.2}
```{r groupOTU, message=FALSE, fig.cap="(ref:groupOTUcap)", fig.scap="(ref:groupOTUscap)", out.extra='', out.width='100%'}
data(iris)
rn <- paste0(iris[,5], "_", 1:150)
rownames(iris) <- rn
d_iris <- dist(iris[,-5], method="man")
tree_iris <- ape::bionj(d_iris)
grp <- list(setosa = rn[1:50],
versicolor = rn[51:100],
virginica = rn[101:150])
p_iris <- ggtree(tree_iris, layout = 'circular', branch.length='none')
groupOTU(p_iris, grp, 'Species') + aes(color=Species) +
theme(legend.position="right")
```
\setstretch{1.5}
We can grouping taxa at tree level. The following code will produce identical figure of Figure \@ref(fig:groupOTU) (see more details described at [session 2.2.3](#grouping-taxa)).
```r
tree_iris <- groupOTU(tree_iris, grp, "Species")
ggtree(tree_iris, aes(color=Species), layout = 'circular', branch.length = 'none') +
theme(legend.position="right")
```
## Exploring tree structure
To facilitate exploring the tree structure, *ggtree* supports rotating selected clade by 180 degree using the `rotate()` function (Figure \@ref(fig:rfClade)B). Position of immediate descendant clades of internal node can be exchanged via `flip()` function (Figure \@ref(fig:rfClade)C).
(ref:rotateCladescap) Exploring tree structure.
(ref:rotateCladecap) **Exploring tree structure.** A clade (indicated by darkgreen circle) in a tree (A) can be rotated by 180° (B) and the positions of its immediate descedant clades (colored by blue and red) can be exchanged (C).
\setstretch{1.2}
```{r echo=T, eval=F}
p1 <- p + geom_point2(aes(subset=node==16), color='darkgreen', size=5)
p2 <- rotate(p1, 17) %>% rotate(21)
flip(p2, 17, 21)
```
```{r rfClade, fig.cap="(ref:rotateCladecap)", fig.scap="(ref:rotateCladescap)", out.extra='', fig.width=7, fig.height=3, echo=F, out.width='100%'}
p1 <- p + geom_tiplab() +
geom_point2(aes(subset=node==16), color='darkgreen', size=5)
p2 <- rotate(p1, 17) %>% rotate(21)
p3 <- flip(p2, 17, 21)
plot_grid(p1, p2, p3, ncol=3, labels = LETTERS[1:3])
```
\setstretch{1.5}
Most of the tree manipulation functions are working on clades, while `r Biocpkg("ggtree")` also provides functions to manipulate a tree, including `open_tree()` to transform a tree in either rectangular or circular layout to fan layout, and `rotate_tree()` function to rotate a tree for specific angle in both circular or fan layouts, as demonstrated in Figure \@ref(fig:openTree) and \@ref(fig:rotateTree).
\setstretch{1.2}
```{r eval=FALSE}
p3 <- open_tree(p, 180) + geom_tiplab()
print(p3)
```
\setstretch{1.5}
(ref:openTreescap) Transforming a tree to fan layout.
(ref:openTreecap) **Transforming a tree to fan layout.** A tree can be transformed to fan layout by `open_tree` with specific *angle* parameter.
```{r openTree, fig.cap="(ref:openTreecap)", fig.scap="(ref:openTreescap)",echo=FALSE, fig.width=6, fig.height=3.5, out.extra=''}
p3 <- open_tree(p, 180) + geom_tiplab()
ggplot() + ylim(0.5, 1) + xlim(0, 1) + theme_tree() +
annotation_custom(ggplotGrob(p3),
xmin=-.2, xmax=1.15, ymin=-.25, ymax=1.3)
```
\setstretch{1.2}
```{r eval=FALSE}
rotate_tree(p3, 180)
```
\setstretch{1.5}
(ref:rotateTreescap) Rotating tree.
(ref:rotateTreecap) **Rotating tree.** A circular/fan layout tree can be rotated by any specific *angle*.
```{r rotateTree, echo=FALSE, fig.cap="(ref:rotateTreecap)", fig.scap="(ref:rotateTreescap)", fig.width=6, fig.height=3.2, out.extra=''}
ggplot() + ylim(0.5, 1) + xlim(0, 1) + theme_tree() +
annotation_custom(ggplotGrob(rotate_tree(p3, 180)),
xmin=-.15, xmax=1.15, ymin=.2, ymax=1.75)
```
The following example traverse all the internal nodes and rotate them one by one (Figure \@ref(fig:rotategif)).
```{r eval=F}
set.seed(2016-05-29)
x <- rtree(50)
p <- ggtree(x) + geom_tiplab()
for (n in reorder(x, 'postorder')$edge[,1] %>% unique) {
p <- rotate(p, n)
print(p + geom_point2(aes(subset=(node == n)), color='red'))
}
```
(ref:rotategifscap) Traverse and rotate all clades.
(ref:rotategifcap) **Traverse and rotate all clades.**
```{r rotategif, fig.width=8, fig.height=9.6, echo=FALSE, fig.cap="(ref:rotategifcap)", fig.scap="(ref:rotategifscap)"}
knitr::include_graphics("img/rotate_clade.gif")
```
```{r eval=FALSE}
set.seed(123)
tr <- rtree(50)
p <- ggtree(tr, layout='circular') + geom_tiplab()
for (angle in seq(0, 270, 10)) {
print(open_tree(p, angle=angle) + ggtitle(paste("open angle:", angle)))
}
```
Figure \@ref(fig:fangif) demonstrates the usage of `open_tree` with different open angles.
(ref:fangifscap) Open tree with different angles.
(ref:fangifcap) **Open tree with different angles.**
```{r fangif, fig.width=8, fig.height=9.6, echo=FALSE, fig.cap="(ref:fangifcap)", fig.scap="(ref:fangifscap)"}
knitr::include_graphics("img/fan_layout.gif")
```
Figure \@ref(fig:rotatetreegif) illustrates rotating tree with different angles.
```{r eval=FALSE}
for (angle in seq(0, 270, 10)) {
print(rotate_tree(p, angle) + ggtitle(paste("rotate angle:", angle)))
}
```
(ref:rotatetreegifscap) Rotate tree with different angles.
(ref:rotatetreegifcap) **Rotate tree with different angles.**
```{r rotatetreegif, fig.width=8, fig.height=9.6, echo=FALSE, fig.cap="(ref:rotatetreegifcap)", fig.scap="(ref:rotatetreegifscap)"}
knitr::include_graphics("img/rotate_tree.gif")
```
Interactive tree manipulation is also possible via [`identify` methods](#identify).
## Summary {#summary6}
The `r Biocpkg("ggtree")` provides a set of functions to allow visually manipulating phylogenetic tree and exploring tree structure with associated data.