forked from YuLab-SMU/treedata-book
-
Notifications
You must be signed in to change notification settings - Fork 0
/
04_ggtree_visualization.Rmd
705 lines (454 loc) · 43.4 KB
/
04_ggtree_visualization.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
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
# (PART\*) Part II: Tree data visualization and annotation {-}
\newpage
# Phylogenetic Tree Visualization {#chapter4}
```{r include=F}
library("ape")
library("grid")
library("ggplot2")
library("cowplot")
library("treeio")
library("ggtree")
```
## Introduction
There are many software packages and web tools that are designed for displaying phylogenetic trees, such as `r pkg_treeview` [@page_visualizing_2002], `r pkg_figtree`\index{FigTree}, `r pkg_treedyn` [@chevenet_treedyn:_2006], *Dendroscope* [@huson_dendroscope_2012], `r pkg_evolview`\index{EvolView} [@he_evolview_2016], and `r pkg_itol`\index{iTOL} [@letunic_interactive_2007], *etc*. Only a few of them, such as `r pkg_figtree`, `r pkg_treedyn` and `r pkg_itol`, allow users to annotate the trees with colored branches, highlighted clades with tree features. However, their pre-defined annotating functions are usually limited to some specific phylogenetic data. As phylogenetic trees are becoming more widely used in multidisciplinary studies, there is an increasing need to incorporate various types of phylogenetic covariates and other associated data from different sources into the trees for visualizations and further analyses. For instance, the influenza virus has a wide host range, diverse and dynamic genotypes, and characteristic transmission behaviors that are mostly associated with the virus's evolution and essentially among themselves. Therefore, in addition to standalone applications that focus on each of the specific analysis and data types, researchers studying molecular evolution need a robust and programmable platform that allows the high levels of integration and visualization of many of these different aspects of data (raw or from other primary analyses) over the phylogenetic trees to identify their associations and patterns.
To fill this gap, we developed `r Biocpkg("ggtree")`\index{ggtree} [@yu_ggtree:_2017], a package for the R programming language [@rstats] released under the Bioconductor\index{Bioconductor} project [@gentleman_bioconductor_2004]. The `r Biocpkg("ggtree")` is built to work with `treedata` objects (see [chapter 1](#chapter1) and [chapter 9](#chapter9)), and display tree graphics with the `r CRANpkg("ggplot2")` package [@wickham_ggplot2_2016] that was based on the grammar of graphics [@wilkinson_grammar_2005].
The R language is increasingly being used in phylogenetics. However, a comprehensive package, designed for viewing and annotating phylogenetic trees, particularly with complex data integration, is not yet available. Most of the R packages in phylogenetics focus on specific statistical analyses rather than viewing and annotating the trees with more generalized phylogeny-associated data. Some packages, including `r CRANpkg("ape")`\index{ape} [@paradis_ape_2004] and `r CRANpkg("phytools")` [@revell_phytools_2012], which are capable of displaying and annotating trees, are developed using the base graphics system of R. In particular, `r CRANpkg("ape")` is one of the fundamental packages for phylogenetic analysis and data processing. However, the base graphics system is relatively difficult to extend and limits the complexity of the tree figure to be displayed. `r CRANpkg("OutbreakTools")` [@jombart_outbreaktools_2014] and `r Biocpkg("phyloseq")` [@mcmurdie_phyloseq_2013] extended `r CRANpkg("ggplot2")` to plot phylogenetic trees. The `r CRANpkg("ggplot2")` system of graphics allows rapid customization and exploration of design solutions. However, these packages were designed for epidemiology and microbiome data respectively and did not aim to provide a general solution for tree visualization\index{visualization} and annotation\index{annotation}. The `r Biocpkg("ggtree")` package also inherits versatile properties of `r CRANpkg("ggplot2")`, and more importantly allows constructing complex tree figures by freely combining multiple layers of annotations (see also [Chapter 5](#chapter5)) using the tree associated data imported from different sources (see detailed in [Chapter 1](#chapter1) and [@wang_treeio_2020]).
## Visualizing Phylogenetic Tree with `r Biocpkg("ggtree")`
The `r Biocpkg("ggtree")` package [@yu_ggtree:_2017] is designed for annotating phylogenetic trees with their associated data of different types and from various sources. These data could come from users or analysis programs and might include evolutionary rates, ancestral sequences\index{ancestral sequences}, *etc.* that are associated with the taxa from real samples, or with the internal nodes representing hypothetic ancestor strain/species, or with the tree branches indicating evolutionary time courses [@wang_treeio_2020]. For instance, the data could be the geographic positions of the sampled avian influenza viruses (informed by the survey locations) and the ancestral nodes (by phylogeographic inference) in the viral gene tree [@lam_phylodynamics_2012].
The `r Biocpkg("ggtree")` supports `r CRANpkg("ggplot2")`'s graphical language, which allows a high level of customization, is intuitive and flexible. Notably, `r CRANpkg("ggplot2")` itself does not provide low-level geometric objects or other support for tree-like structures, and hence `r Biocpkg("ggtree")` is a useful extension in that regard. Even though the other two phylogenetics-related R packages, `r CRANpkg("OutbreakTools")`, and `r Biocpkg("phyloseq")`, are developed based on `r CRANpkg("ggplot2")`, the most valuable part of the `r CRANpkg("ggplot2")`\index{ggplot2} syntax - adding layers of annotations - is not supported in these packages. For example, if we have plotted a tree without taxa labels, `r CRANpkg("OutbreakTools")` and `r Biocpkg("phyloseq")` provide no easy way for general `R` users, who have little knowledge about the infrastructures of these packages, to add a layer of taxa labels. The `r Biocpkg("ggtree")` extends `r CRANpkg("ggplot2")` to support tree objects by implementing a geometric layer, `geom_tree()`, to support visualizing tree structure. In `r Biocpkg("ggtree")`, viewing a phylogenetic tree is relatively easy, via the command `ggplot(tree_object) + geom_tree() + theme_tree()` or `ggtree(tree_object)` for short. Layers of annotations can be added one-by-one via the `+` operator. To facilitate tree visualization, `r Biocpkg("ggtree")` provides several geometric layers, including `geom_treescale()` for adding legend of tree branch scale (genetic distance, divergence time, *etc.*), `geom_range()` for displaying uncertainty of branch lengths (confidence interval or range, *etc.*), `geom_tiplab()` for adding taxa label, `geom_tippoint()` and `geom_nodepoint()` for adding symbols of tips and internal nodes, `geom_hilight()` for highlighting clades with rectangle, and `geom_cladelab()` for annotating selected clades with bar and text label, *etc.*. A full list of geometric layers provided by `r Biocpkg("ggtree")` is summarized in Table \@ref(tab:geoms).
To view a phylogenetic tree, we first need to parse the tree file into `R`.
The `r Biocpkg("treeio")` package is able to parse diverse annotation data from different software outputs into `S4` phylogenetic data objects (see also [Chapter 1](#chapter1)). The `r Biocpkg("ggtree")` package mainly utilizes these `S4` objects to display and annotate the tree. Other R packages defined `S3`/`S4` classes to store phylogenetic trees with domain-specific associated data, including `phylo4` and `phylo4d` defined in the `r CRANpkg("phylobase")` package, `obkdata` defined in the `r CRANpkg("OutbreakTools")` package, and `phyloseq` defined in the `r Biocpkg("phyloseq")` package, *etc*. All these tree objects are also supported in `r Biocpkg("ggtree")` and their specific annotation data can be used to annotate the tree directly in `r Biocpkg("ggtree")` (see also [Chapter 9](#chapter9)). Such compatibility of `r Biocpkg("ggtree")` facilitates the integration of data and analysis results. In addition, `r Biocpkg("ggtree")` also supports other tree-like structures, including [dendrogram](#dendrogram) and [tree graphs](#igraph).
### Basic Tree Visualization
The `r Biocpkg('ggtree')` package extends `r CRANpkg('ggplot2')` [@wickham_ggplot2_2016] package to support viewing a phylogenetic tree.
It implements `geom_tree()` layer for displaying a phylogenetic tree, as shown below in Figure \@ref(fig:basicviz)A.
```{r fig.width=3, fig.height=3, fig.align="center", eval=F}
library("treeio")
library("ggtree")
nwk <- system.file("extdata", "sample.nwk", package="treeio")
tree <- read.tree(nwk)
ggplot(tree, aes(x, y)) + geom_tree() + theme_tree()
```
The function, `ggtree()`, was implemented as a shortcut to visualize a tree, and it works exactly the same as shown above.
The `r Biocpkg('ggtree')` package takes all the advantages of `r CRANpkg('ggplot2')`. For example, we can change the color, size, and type of the lines as we do with `r CRANpkg('ggplot2')` (Figure \@ref(fig:basicviz)B).
```{r fig.width=3, fig.height=3, fig.align="center", eval=F}
ggtree(tree, color="firebrick", size=2, linetype="dotted")
```
By default, the tree is viewed in ladderize form, user can set the parameter `ladderize = FALSE` to disable it (Figure \@ref(fig:basicviz)C, see also [FAQ A.5](#branch-setting)).
```{r fig.width=3, fig.height=3, fig.align="center", eval=F}
ggtree(tree, ladderize=FALSE)
```
The `branch.length` is used to scale the edge, user can set the parameter `branch.length = "none"` to only view the tree topology (cladogram, Figure \@ref(fig:basicviz)D) or other numerical variables to scale the tree (*e.g.*, _d~N~/d~S~_, see also in [Chapter 5](#chapter5)).
```{r fig.width=3, fig.height=3, fig.align="center", eval=F}
ggtree(tree, branch.length="none")
```
(ref:basicvizscap) Basic tree visualization.
(ref:basicvizcap) **Basic tree visualization.** Default ggtree output with ladderized effect (A), non-variable setting (*e.g.*, color, size, line type) (B), non-ladderized tree (C), cladogram that only displays tree topology without branch length information (D).
```{r basicviz, fig.width=12, fig.height=3, echo=F, fig.cap="(ref:basicvizcap)", fig.scap="(ref:basicvizscap)", out.width="100%"}
library("treeio")
library("ggtree")
nwk <- system.file("extdata", "sample.nwk", package="treeio")
tree <- read.tree(nwk)
aplot::plot_list(
ggplot(tree, aes(x, y)) + geom_tree() + theme_tree(),
ggtree(tree, color="firebrick", size=2, linetype="dotted"),
ggtree(tree, ladderize=FALSE),
ggtree(tree, branch.length="none"),
ncol=4, tag_levels='A')
```
### Layouts of a phylogenetic tree {#tree-layouts}
Viewing phylogenetic with `r Biocpkg("ggtree")` is quite simple, just pass the tree object to the `ggtree()` function. We have developed several types of layouts for tree presentation (Figure \@ref(fig:layout)), including *rectangular* (by default), *roundrect* (rounded rectangular), *ellipse*, *slanted*, *circular*, *fan*, *unrooted*\index{unrooted} (equal angle and daylight methods), time-scaled, and two-dimensional layouts.
Here are examples of visualizing a tree with different layouts:
```{r eval=F}
library(ggtree)
set.seed(2017-02-16)
tree <- rtree(50)
ggtree(tree)
ggtree(tree, layout="roundrect")
ggtree(tree, layout="slanted")
ggtree(tree, layout="ellipse")
ggtree(tree, layout="circular")
ggtree(tree, layout="fan", open.angle=120)
ggtree(tree, layout="equal_angle")
ggtree(tree, layout="daylight")
ggtree(tree, branch.length='none')
ggtree(tree, layout="ellipse", branch.length="none")
ggtree(tree, branch.length='none', layout='circular')
ggtree(tree, layout="daylight", branch.length = 'none')
```
(ref:layoutscap) Tree layouts.
(ref:layoutcap) **Tree layouts.** Phylogram: rectangular layout (A), rounded rectangular layout (B), slanted layout (C), ellipse layout (D), circular layout (E), and fan layout (F). Unrooted: equal-angle method (G) and daylight method (H). Cladogram: rectangular layout (I), ellipse (J), circular layout (K), and unrooted layout (L). Slanted and fan layouts for cladogram are also supported.
```{r layout, echo=F, fig.width=12, fig.height=9, fig.cap="(ref:layoutcap)", fig.scap="(ref:layoutscap)", out.extra='', message=FALSE, out.width="100%"}
library(ggtree)
library(cowplot)
set.seed(2017-02-16)
tree <- rtree(50)
p1 <- ggtree(tree, layout="circular")
p2 <- ggtree(tree, layout="fan", open.angle=120)
#p1 <- ggplotify::as.ggplot(p1, scale=1.05)
#p2 <- ggplotify::as.ggplot(p2, scale=1.05)
playout <- plot_grid(
ggtree(tree), # + ggtitle("rectangular layout")+theme(plot.title = element_text(hjust = 0.5)),
ggtree(tree, layout="roundrect"),
ggtree(tree, layout="slanted"), # + ggtitle("slanted layout")+theme(plot.title = element_text(hjust = 0.5)),
ggtree(tree, layout="ellipse"),
p1, # + ggtitle("circular layout")+theme(plot.title = element_text(hjust = 0.5), plot.margin = unit(c(0,0,0,0), "lines")),
p2, # + ggtitle("fan layout")+theme(plot.title = element_text(hjust = 0.5), plot.margin = unit(c(0,0,0,0), "lines")),
ggtree(tree, layout="equal_angle"),
ggtree(tree, layout="daylight"),
ggtree(tree, branch.length='none'),
ggtree(tree, layout="ellipse", branch.length="none"),
ggtree(tree, branch.length='none', layout='circular'),
ggtree(tree, layout="daylight", branch.length = 'none'),
ncol=4, labels = LETTERS[1:12])
# save(playout, file="data/playout.rda")
playout
```
Other possible layouts that can be drawn by modifying
scales/coordination (Figure \@ref(fig:layout2)).
<!-- for examples, [reverse label of time
scale](https://github.com/GuangchuangYu/ggtree/issues/87), [repropotion
circular/fan tree](
https://groups.google.com/d/msg/bioc-ggtree/UoGQekWHIvw/ZswUUZKSGwAJ), *etc.*. -->
```{r eval=FALSE}
ggtree(tree) + scale_x_reverse()
ggtree(tree) + coord_flip()
ggtree(tree) + layout_dendrogram()
ggplotify::as.ggplot(ggtree(tree), angle=-30, scale=.9)
ggtree(tree, layout='slanted') + coord_flip()
ggtree(tree, layout='slanted', branch.length='none') + layout_dendrogram()
ggtree(tree, layout='circular') + xlim(-10, NA)
ggtree(tree) + layout_inward_circular()
ggtree(tree) + layout_inward_circular(xlim=15)
```
```{r fig.keep='none', echo=FALSE, warning=FALSE}
# tree_angle <- grid::grid.grabExpr(print(ggtree(tree), newpage=TRUE, vp = grid::viewport(angle=-30, width=.9, height=.9)))
tree_angle <- ggplotify::as.ggplot(ggtree(tree), angle=-30, scale=.9)
```
(ref:layout2scap) Derived Tree layouts.
(ref:layout2cap) **Derived Tree layouts.** right-to-left rectangular layout (A), bottom-up rectangular layout (B), top-down rectangular layout (Dendrogram) (C), rotated rectangular layout (D), bottom-up slanted layout (E), top-down slanted layout (Cladogram) (F), circular layout (G), circular inward layout (H and I).
```{r layout2, fig.cap="(ref:layout2cap)", fig.scap="(ref:layout2scap)", fig.width=8, fig.height = 8, echo=FALSE, warning=FALSE, out.width="100%"}
plot_grid(
ggtree(tree) + scale_x_reverse(),
ggtree(tree) + coord_flip(),
ggtree(tree) + layout_dendrogram(),
tree_angle,
ggtree(tree, layout='slanted') + coord_flip(),
ggtree(tree, layout='slanted', branch.length='none') + layout_dendrogram(),
ggtree(tree, layout='circular') + xlim(-10, NA),
# ggtree(tree) + scale_x_reverse() + coord_polar(theta='y'),
# ggtree(tree) + scale_x_reverse(limits=c(15, 0)) + coord_polar(theta='y'),
ggtree(tree) + layout_inward_circular(),
ggtree(tree) + layout_inward_circular(xlim=15),
ncol=3, labels=LETTERS[1:9])
```
**Phylogram.** Layouts of *rectangular*, *roundrect*, *slanted*, *ellipse*, *circular*, and *fan* are supported to visualize phylogram\index{phylogram} (by default, with branch length scaled) as demonstrated in Figures \@ref(fig:layout)A-F.
**Unrooted layout.** Unrooted (also called 'radial') layout is supported by equal-angle and daylight algorithms: users can specify unrooted layout algorithm by passing "equal_angle" or "daylight" to `layout` parameter to visualize the tree. The equal-angle method was proposed by Christopher Meacham in *PLOTREE*, which was incorporated in `r pkg_phylip` [@retief_phylogenetic_2000]. This method starts from the root of the tree and allocates arcs of angle to each subtree proportional to the number of tips in it. It iterates from root to tips and subdivides the angle allocated to a subtree into angles for its dependent subtrees. This method is fast and was implemented in many software packages. As shown in Figure \@ref(fig:layout)G, the equal angle method has a drawback that tips tend to be clustered together, which will leave many spaces unused. The daylight method starts from an initial tree built by equal angle and iteratively improves it by successively going to each interior node and swinging subtrees so that the arcs of "daylight" are equal (Figure \@ref(fig:layout)H). This method was firstly implemented in `r pkg_paup` [@wilgenbusch_inferring_2003].
**Cladogram.** To visualize a cladogram\index{cladogram} that is without branch length scaling and only displays the tree structure, `branch.length` is set to "none" and it works for all types of layouts (Figures \@ref(fig:layout)I-L).
**Time-scaled layout.** For a time-scaled tree\index{time-scaled tree}, the most recent sampling date must be specified via the `mrsd` parameter, and `ggtree()` will scale the tree by sampling (tip) and divergence (internal node) time, and a time scale axis will be displayed under the tree by default. Users can use the `r CRANpkg("deeptime")` package to add geologic time scale (e.g., periods and eras) to a `ggtree()` plot.
(ref:timescaledscap) Time-scaled layout.
(ref:timescaledcap) **Time-scaled layout.** The *x-axis* is the timescale (in units of the year). The divergence time in this example was inferred by `r pkg_beast` using the molecular clock model.
```{r timescaled, fig.cap="(ref:timescaledcap)", fig.scap="(ref:timescaledscap)", out.extra='', fig.height=4.5}
beast_file <- system.file("examples/MCC_FluA_H3.tree",
package="ggtree")
beast_tree <- read.beast(beast_file)
ggtree(beast_tree, mrsd="2013-01-01") + theme_tree2()
```
**Two-dimensional tree layout.** A two-dimensional tree\index{two-dimensional tree} is a projection of the phylogenetic tree in a space defined by the associated phenotype (numerical or categorical trait, on the _y_-axis) and tree branch scale (*e.g.*, evolutionary distance, divergent time, on the _x_-axis). The phenotype can be a measure of certain biological characteristics of the taxa and hypothetical ancestors in the tree. This layout is useful to track the virus phenotypes or other behaviors (*y*-axis) changing with the virus evolution (*x*-axis). In fact, the analysis of phenotypes or genotypes over evolutionary time have been widely used for study of influenza virus evolution [@neher_prediction_2016], though such analysis diagrams are not tree-like, *i.e.*, no connection between data points, unlike our two-dimensional tree layout that connects data points with the corresponding tree branches. Therefore, this new layout we provided will make such data analysis easier and more scalable for large sequence data-sets.
In this example, we used the previous time-scaled tree of H3 human and swine influenza viruses (Figure \@ref(fig:timescaled); data published in [@liang_expansion_2014]) and scaled the *y*-axis based on the predicted *N*-linked glycosylation sites (NLG) for each of the taxon and ancestral sequences of hemagglutinin proteins. The NLG sites were predicted using the [NetNGlyc 1.0 Server](http://www.cbs.dtu.dk/services/NetNGlyc/). To scale the *y*-axis, the parameter `yscale` in the `ggtree()` function is set to a numerical or categorical variable. If `yscale` is a categorical variable as in this example, users should specify how the categories are to be mapped to numerical values via the `yscale_mapping` variables.
(ref:2dscap) Two-dimensional tree layout.
(ref:2dcap) **Two-dimensional tree layout.** The trunk and other branches are highlighted in red (for swine) and blue (for humans). The *x*-axis is scaled to the branch length (in units of year) of the time-scaled tree. The *y*-axis is scaled to the node attribute variable, in this case, the number of predicted *N*-linked glycosylation sites (NLG) on the hemagglutinin protein. Colored circles indicate the different types of tree nodes. Note that nodes assigned the same *x*- (temporal) and *y*- (NLG) coordinates are superimposed in this representation and appear as one node, which is shaded based on the colors of all the nodes at that point.
```{r 2d, fig.cap="(ref:2dcap)", fig.width=8.5, fig.height=5, fig.scap="(ref:2dscap)", out.extra='', out.width='100%'}
NAG_file <- system.file("examples/NAG_inHA1.txt", package="ggtree")
NAG.df <- read.table(NAG_file, sep="\t", header=FALSE,
stringsAsFactors = FALSE)
NAG <- NAG.df[,2]
names(NAG) <- NAG.df[,1]
## separate the tree by host species
tip <- as.phylo(beast_tree)$tip.label
beast_tree <- groupOTU(beast_tree, tip[grep("Swine", tip)],
group_name = "host")
p <- ggtree(beast_tree, aes(color=host), mrsd="2013-01-01",
yscale = "label", yscale_mapping = NAG) +
theme_classic() + theme(legend.position='none') +
scale_color_manual(values=c("blue", "red"),
labels=c("human", "swine")) +
ylab("Number of predicted N-linked glycoslyation sites")
## (optional) add more annotations to help interpretation
p + geom_nodepoint(color="grey", size=3, alpha=.8) +
geom_rootpoint(color="black", size=3) +
geom_tippoint(size=3, alpha=.5) +
annotate("point", 1992, 5.6, size=3, color="black") +
annotate("point", 1992, 5.4, size=3, color="grey") +
annotate("point", 1991.6, 5.2, size=3, color="blue") +
annotate("point", 1992, 5.2, size=3, color="red") +
annotate("text", 1992.3, 5.6, hjust=0, size=4, label="Root node") +
annotate("text", 1992.3, 5.4, hjust=0, size=4,
label="Internal nodes") +
annotate("text", 1992.3, 5.2, hjust=0, size=4,
label="Tip nodes (blue: human; red: swine)")
```
As shown in Figure \@ref(fig:2d), a two-dimensional tree is good at visualizing the change of phenotype over the evolution in the phylogenetic tree. In this example, it is shown that the H3 gene of the human influenza A virus maintained a high level of *N*-linked glycosylation sites (n=8 to 9) over the last two decades and dropped significantly to 5 or 6 in a separate viral lineage transmitted to swine populations and established there. It was indeed hypothesized that the human influenza virus with a high level of glycosylation on the viral hemagglutinin protein provides a better shielding effect to protect the antigenic sites from exposure to the herd immunity, and thus has a selective advantage in human populations that maintain a high level of herd immunity against the circulating human influenza virus strains. For the viral lineage that newly jumped across the species barrier and transmitted to the swine population, the shielding effect of the high-level surface glycan oppositely imposes selective disadvantage because the receptor-binding domain may also be shielded which greatly affects the viral fitness of the lineage that newly adapted to a new host species. Another example of a two-dimensional tree can be found in Figure \@ref(fig:phenogram).
## Displaying Tree Components
### Displaying tree scale (evolution distance) {#geom-trescale}
To show tree scale, the user can use `geom_treescale()` layer (Figures \@ref(fig:treescale)A-C).
```{r fig.width=4, fig.height=4, fig.align="center", eval=F}
ggtree(tree) + geom_treescale()
```
`geom_treescale()` supports the following parameters:
+ *x* and *y* for tree scale position
+ *width* for the length of the tree scale
+ *fontsize* for the size of the text
+ *linesize* for the size of the line
+ *offset* for relative position of the line and the text
+ *color* for color of the tree scale
```{r eval=F}
ggtree(tree) + geom_treescale(x=0, y=45, width=1, color='red')
ggtree(tree) + geom_treescale(fontsize=6, linesize=2, offset=1)
```
We can also use `theme_tree2()` to display the tree scale by adding *x axis* (Figure \@ref(fig:treescale)D).
```{r fig.width=3, fig.height=3, fig.align="center", eval=F}
ggtree(tree) + theme_tree2()
```
(ref:treescalescap) Display tree scale.
(ref:treescalecap) **Display tree scale.** `geom_treescale()` automatically add a scale bar for evolutionary distance (A). Users can modify the color, width, and position of the scale (B) as well as the size of the scale bar and text and their relative position (C). Another possible solution is to enable the *x*-axis which is useful for the time-scaled tree (D).
```{r treescale, fig.width=8, fig.height=6, echo=F, fig.cap="(ref:treescalecap)", fig.scap="(ref:treescalescap)", out.width='100%'}
cowplot::plot_grid(
ggtree(tree) + geom_treescale(),
ggtree(tree)+geom_treescale(x=0, y=45, width=1, color='red'),
ggtree(tree)+geom_treescale(fontsize=6, linesize=2, offset=1),
ggtree(tree) + theme_tree2(),
ncol=2, labels=LETTERS[1:4])
```
Tree scale is not restricted to evolution distance, `r Biocpkg('treeio')` can re-scale the tree with other numerical variables (details described in [session 2.4](#rescale-treeio)), and `r Biocpkg("ggtree")` allows users to specify a numerical variable to serve as branch length for visualization (details described in [session 4.3](#rescale-tree)).
### Displaying nodes/tips {#geom-nodepoint}
Showing all the internal nodes and tips in the tree can be done by adding a layer of points using `geom_nodepoint()`, `geom_tippoint()`, or `geom_point()` (Figure \@ref(fig:nodeTip)).
```{r fig.width=3, fig.height=3, fig.align="center", eval=F}
ggtree(tree) +
geom_point(aes(shape=isTip, color=isTip), size=3)
p <- ggtree(tree) +
geom_nodepoint(color="#b5e521", alpha=1/4, size=10)
p + geom_tippoint(color="#FDAC4F", shape=8, size=3)
```
(ref:nodeTipscap) Display external and internal nodes.
(ref:nodeTipcap) **Display external and internal nodes.** `geom_point()` automatically add symbolic points of all nodes (A). `geom_nodepoint()` adds symbolic points for internal nodes and `geom_tippoint()` adds symbolic points for external nodes (B).
```{r nodeTip, fig.width=8, fig.height=3, echo=F, fig.cap="(ref:nodeTipcap)", fig.scap="(ref:nodeTipscap)", out.width='100%'}
p1 <- ggtree(tree) + geom_point(aes(shape=isTip, color=isTip), size=3)
p <- ggtree(tree) + geom_nodepoint(color="#b5e521", alpha=1/4, size=10)
p2 <- p + geom_tippoint(color="#FDAC4F", shape=8, size=3)
plot_list(p1, p2, ncol=2, tag_levels='A')
```
### Displaying labels
Users can use `geom_text()` or `geom_label()` to display the node (if available) and tip labels simultaneously or `geom_tiplab()` to only display tip labels (Figure \@ref(fig:tiplab)A).
```{r fig.width=3, fig.height=3, warning=FALSE, fig.align="center", eval=FALSE}
p + geom_tiplab(size=3, color="purple")
```
The `geom_tiplab()` layer not only supports using *text* or *label* geom to display labels, but
it also supports *image* geom to label tip with image files (see [Chapter 7](#chapter7)). A corresponding
geom, `geom_nodelab()` is also provided for displaying node labels.
For *circular* and *unrooted* layouts, `r Biocpkg('ggtree')` supports rotating node labels according to the angles of the branches (Figure \@ref(fig:tiplab)B).
```{r fig.width=6, fig.height=6, warning=FALSE, fig.align="center", eval=FALSE}
ggtree(tree, layout="circular") + geom_tiplab(aes(angle=angle), color='blue')
```
For long tip labels, the label may be truncated. There are several ways to solve this issue (see [FAQ: Tip label truncated](#faq-label-truncated)). Another solution to solve this issue is to display tip labels as *y*-axis labels (Figure \@ref(fig:tiplab)C). However, it only works for rectangular and dendrogram layouts and users need to use `theme()` to adjust tip labels in this case.
```{r fig.width=6, fig.height=6, warning=FALSE, fig.align="center", eval=FALSE}
ggtree(tree) + geom_tiplab(as_ylab=TRUE, color='firebrick')
```
(ref:tiplabscap) Display tip labels.
(ref:tiplabcap) **Display tip labels.** `geom_tiplab()` supports displaying tip labels (A). For the circular, fan, or unrooted tree layouts, the labels can be rotated to fit the angle of the branches (B). For dendrogram/rectangular layout, tip labels can be displayed as *y*-axis labels (C).
```{r tiplab, fig.width=13.5, fig.height=5.5, echo=F, fig.cap="(ref:tiplabcap)", fig.scap="(ref:tiplabscap)", out.width='100%'}
p1 <- p + geom_tiplab(size=3, color="purple")
p2 <- ggtree(tree, layout="circular") + geom_tiplab(aes(angle=angle), color='blue')
p2 = ggplotify::as.ggplot(p2 + ggimage::theme_transparent(), scale=1.3, hjust=-.1, vjust=.05)
p3 <- ggtree(tree) + geom_tiplab(as_ylab=TRUE, color='firebrick')
plot_list(p1, p2, p3, ncol=3, tag_levels='A', widths=c(1.1, 2, 1))
```
By default, the positions to display text are based on the node positions; we can change them to be based on the middle of the branch/edge (by setting `aes(x = branch)`), which is very useful when annotating transition from the parent node to the child node.
### Displaying root edge
The `ggtree()` doesn't plot the root-edge by default. Users can use `geom_rootedge()` to automatically display the root-edge (Figure \@ref(fig:rootedge)A). If there is no root edge information, `geom_rootedge()` will display nothing by default (Figure \@ref(fig:rootedge)B). Users can set the root-edge to the tree (Figure \@ref(fig:rootedge)C) or specify `rootedge` in `geom_rootedge()` (Figure \@ref(fig:rootedge)D). A long root length is useful to increase readability of the circular tree (see also [FAQ: Enlarge center space](#faq-enlarge-center-space)).
```{r eval=F}
## with root edge = 1
tree1 <- read.tree(text='((A:1,B:2):3,C:2):1;')
ggtree(tree1) + geom_tiplab() + geom_rootedge()
## without root edge
tree2 <- read.tree(text='((A:1,B:2):3,C:2);')
ggtree(tree2) + geom_tiplab() + geom_rootedge()
## setting root edge
tree2$root.edge <- 2
ggtree(tree2) + geom_tiplab() + geom_rootedge()
## specify the length of root edge for just plotting
## this will ignore tree$root.edge
ggtree(tree2) + geom_tiplab() + geom_rootedge(rootedge = 3)
```
(ref:rootedgescap) Display root edge.
(ref:rootedgecap) **Display root edge.** `geom_rootedge()` supports displaying root edge if the root edge was presented (A). It shows nothing if there is no root edge (B). In this case, users can manually set the root edge for the tree (C) or just specify the length of the root for plotting (D).
```{r rootedge, fig.width=6, fig.height=4, echo=F, fig.cap="(ref:rootedgecap)", fig.scap="(ref:rootedgescap)"}
## with root edge = 1
tree1 <- read.tree(text='((A:1,B:2):3,C:2):1;')
p1 = ggtree(tree1) + geom_tiplab() + geom_rootedge()
## without root edge
tree2 <- read.tree(text='((A:1,B:2):3,C:2);')
p2 = ggtree(tree2) + geom_tiplab() + geom_rootedge()
## setting root edge
tree2$root.edge <- 2
p3 = ggtree(tree2) + geom_tiplab() + geom_rootedge()
## specify length of root edge for just plotting
## this will ignore tree$root.edge
p4 = ggtree(tree2) + geom_tiplab() + geom_rootedge(rootedge = 3)
cowplot::plot_grid(p1, p2, p3, p4, ncol=2, labels = LETTERS[1:4])
```
### Color tree
In `r Biocpkg("ggtree")` [@yu_two_2018], coloring phylogenetic tree is easy, by using `aes(color=VAR)` to map the color of the tree based on a specific variable (both numerical and categorical variables are supported, see Figure \@ref(fig:colortree)).
(ref:colortreescap) Color tree by continuous or discrete feature.
(ref:colortreecap) **Color tree by continuous or discrete feature.** Edges are colored by values associated with the child nodes.
```{r colortree, fig.width=5, fig.height=5, fig.cap="(ref:colortreecap)", fig.scap="(ref:colortreescap)"}
ggtree(beast_tree, aes(color=rate)) +
scale_color_continuous(low='darkgreen', high='red') +
theme(legend.position="right")
```
Users can use any feature (if available), including clade posterior and _d~N~/d~S~_, _etc._, to scale the color of the tree. If the feature is a continuous numerical value, `r Biocpkg("ggtree")` provides a `continuous` parameter to support plotting continuous state transition in edges. Here, we use an example^[<http://www.phytools.org/eqg2015/asr.html>] to demonstrate this functionality (Figure \@ref(fig:continuousColor)A). If you want to add a thin black border in tree branches, you can place a tree with black and slightly thicker branches below your tree to emulate edge outlines as demonstrated in Figure \@ref(fig:continuousColor)B.
(ref:continuousColorscap) Continuous state transition in edges.
(ref:continuousColorcap) **Continuous state transition in edges.** Edges are colored by the values from ancestral trait to offspring.
```{r continuousColor, fig.width=12, fig.height=6, fig.cap="(ref:continuousColorcap)", fig.scap="(ref:continuousColorscap)", out.width='100%'}
library(ggtree)
library(treeio)
library(tidytree)
library(ggplot2)
library(TDbook)
## ref: http://www.phytools.org/eqg2015/asr.html
##
## load `tree_anole` and `df_svl` from 'TDbook'
svl <- as.matrix(df_svl)[,1]
fit <- phytools::fastAnc(tree_anole, svl, vars=TRUE, CI=TRUE)
td <- data.frame(node = nodeid(tree_anole, names(svl)),
trait = svl)
nd <- data.frame(node = names(fit$ace), trait = fit$ace)
d <- rbind(td, nd)
d$node <- as.numeric(d$node)
tree <- full_join(tree_anole, d, by = 'node')
p1 <- ggtree(tree, aes(color=trait), layout = 'circular',
ladderize = FALSE, continuous = 'colour', size=2) +
scale_color_gradientn(colours=c("red", 'orange', 'green', 'cyan', 'blue')) +
geom_tiplab(hjust = -.1) +
xlim(0, 1.2) +
theme(legend.position = c(.05, .85))
p2 <- ggtree(tree, layout='circular', ladderize = FALSE, size=2.8) +
geom_tree(aes(color=trait), continuous = 'colour', size=2) +
scale_color_gradientn(colours=c("red", 'orange', 'green', 'cyan', 'blue')) +
geom_tiplab(aes(color=trait), hjust = -.1) +
xlim(0, 1.2) +
theme(legend.position = c(.05, .85))
plot_list(p1, p2, ncol=2, tag_levels="A")
```
Besides, we can use a two-dimensional tree (as demonstrated in Figure \@ref(fig:2d)) to visualize phenotype on the vertical dimension to create the phenogram Figure \@ref(fig:phenogram). We can use the `r CRANpkg("ggrepel")` package to repel tip labels to avoid overlapping as demonstrated in Figure \@ref(fig:repelTip).
(ref:phenogramscap) Phenogram.
(ref:phenogramcap) **Phenogram.** Projecting the tree into a space defined by time (or genetic distance) on the horizontal axis and phenotype on the vertical dimension.
```{r phenogram, fig.width=6, fig.height=8, fig.cap="(ref:phenogramcap)", fig.scap="(ref:phenogramscap)"}
ggtree(tree, aes(color=trait), continuous = 'colour', yscale = "trait") +
scale_color_viridis_c() + theme_minimal()
```
### Rescale tree
Most of the phylogenetic trees are scaled by evolutionary distance (substitution/site). In `r Biocpkg("ggtree")`, users can re-scale a phylogenetic tree by any numerical variable inferred by evolutionary analysis (*e.g.*, _d~N~/d~S~_).
This example displays a time tree (Figure \@ref(fig:rescaleTree)A) and the branches were rescaled by substitution rate inferred by BEAST (Figure \@ref(fig:rescaleTree)B).
```{r rescaleBeast, fig.width=10, fig.height=5}
library("treeio")
beast_file <- system.file("examples/MCC_FluA_H3.tree", package="ggtree")
beast_tree <- read.beast(beast_file)
beast_tree
p1 <- ggtree(beast_tree, mrsd='2013-01-01') + theme_tree2() +
labs(caption="Divergence time")
p2 <- ggtree(beast_tree, branch.length='rate') + theme_tree2() +
labs(caption="Substitution rate")
```
The following example draws a tree inferred by CodeML (Figure \@ref(fig:rescaleTree)C), and the branches can be rescaled by using _d~N~/d~S~_ values (Figure \@ref(fig:rescaleTree)D).
```{r rescaleCodeml, fig.width=10, fig.height=5}
mlcfile <- system.file("extdata/PAML_Codeml", "mlc", package="treeio")
mlc_tree <- read.codeml_mlc(mlcfile)
p3 <- ggtree(mlc_tree) + theme_tree2() +
labs(caption="nucleotide substitutions per codon")
p4 <- ggtree(mlc_tree, branch.length='dN_vs_dS') + theme_tree2() +
labs(caption="dN/dS tree")
```
(ref:rescaleTreescap) Rescale tree branches.
(ref:rescaleTreecap) **Rescale tree branches.** A time-scaled tree inferred by BEAST (A) and its branches were rescaled by substitution rate (B). A tree was inferred by CodeML (C) and the branches were rescaled by _d~N~/d~S~_ values (D).
```{r rescaleTree, fig.width=8, fig.height=6, echo=FALSE,fig.cap="(ref:rescaleTreecap)", fig.scap="(ref:rescaleTreescap)", out.width='100%'}
plot_list(p1, p2, p3, p4, ncol=2, tag_levels='A')
```
This provides a very convenient way to allow us to explore the relationship between tree associated data and tree structure through visualization.
In addition to specifying `branch.length` in tree visualization, users can change branch length stored in tree object by using `rescale_tree()` function provided by the `r Biocpkg("treeio")` package [@wang_treeio_2020], and the following command will display a tree that is identical to (Figure \@ref(fig:rescaleTree)B). The `rescale_tree()` function was documented in [session 2.4](#rescale-treeio).
```{r rescaleBeast2, eval=F}
beast_tree2 <- rescale_tree(beast_tree, branch.length='rate')
ggtree(beast_tree2) + theme_tree2()
```
### Modify components of a theme
The `theme_tree()` defined a totally blank canvas, while `theme_tree2()` adds
phylogenetic distance (via *x*-axis). These two themes all accept a parameter of
`bgcolor` that defined the background color. Users can use any [theme components](http://ggplot2.tidyverse.org/reference/theme.html) to the `theme_tree()` or `theme_tree2()` functions to modify them (Figure \@ref(fig:theme)).
```{r eval=F}
set.seed(2019)
x <- rtree(30)
ggtree(x, color="#0808E5", size=1) + theme_tree("#FEE4E9")
ggtree(x, color="orange", size=1) + theme_tree('grey30')
```
(ref:themescap) Tree themes.
(ref:themecap) **Three themes.** All ggplot2 theme components can be modified, and all the ggplot2 themes can be applied to `ggtree()` output.
```{r theme, fig.width=8, fig.height=3, fig.align="center", echo=FALSE,fig.cap="(ref:themecap)", fig.scap="(ref:themescap)", out.width="100%"}
library(ggimage)
set.seed(2019)
x <- rtree(30)
cowplot::plot_grid(
ggtree(x, color="#0808E5", size=1) + theme_tree("#FEE4E9"),
ggtree(x, color="orange", size=1) + theme_tree('grey30'),
ncol=2)
```
Users can also use an image file as the tree background, see example in [Appendix B](#ggimage-bgimage).
## Visualize a List of Trees
The `r Biocpkg("ggtree")` supports `multiPhylo` and `treedataList` objects and a list of trees can be viewed simultaneously. The trees will visualize one on top of another and can be plotted in different panels through `facet_wrap()` or `facet_grid()` functions (Figure \@ref(fig:multiPhylo)).
(ref:multiPhyloscap) Visualizing multiPhylo object.
(ref:multiPhylocap) **Visualizing multiPhylo object.** The `ggtree()` function supports visualizing multiple trees stored in the `multiPhylo` or `treedataList` objects.
```{r multiPhylo, fig.width=12, fig.height=4,fig.cap="(ref:multiPhylocap)", fig.scap="(ref:multiPhyloscap)", out.width='100%'}
## trees <- lapply(c(10, 20, 40), rtree)
## class(trees) <- "multiPhylo"
## ggtree(trees) + facet_wrap(~.id, scale="free") + geom_tiplab()
f <- system.file("extdata/r8s", "H3_r8s_output.log", package="treeio")
r8s <- read.r8s(f)
ggtree(r8s) + facet_wrap( ~.id, scale="free") + theme_tree2()
```
One hundred bootstrap trees can also be viewed simultaneously (Figure \@ref(fig:bp100)). This allows researchers to explore a large set of phylogenetic trees to find consensus and distinct trees. The consensus tree can be summarized via a density tree (Figure \@ref(fig:densiTree)).
(ref:bp100scap) Visualizing one hundred bootstrap trees simultaneously.
(ref:bp100cap) **Visualizing one hundred bootstrap trees simultaneously.**
```{r bp100, fig.width=20, fig.height=20, fig.cap="(ref:bp100cap)", fig.scap="(ref:bp100scap)", out.width='100%'}
btrees <- read.tree(system.file("extdata/RAxML",
"RAxML_bootstrap.H3",
package="treeio")
)
ggtree(btrees) + facet_wrap(~.id, ncol=10)
```
### Annotate one tree with values from different variables
To annotate one tree (the same tree) with the values from different variables, one can plot them separately and use `r CRANpkg("patchwork")` or `r CRANpkg("aplot")` to combine them side-by-side.
Another solution is to utilize the ability to plot a list of trees by `r Biocpkg("ggtree")`, and then add annotation layers for the selected variable at a specific panel via the [subset](#geom2) aesthetic mapping supported by `r Biocpkg("ggtree")` or using the `td_filter()` as demonstrated in Figure \@ref(fig:onetreefacet). The `.id` is the conserved variable that is internally used to store the IDs of different trees.
(ref:onetreefacetscap) Annotate one tree with values from different variables.
(ref:onetreefacetcap) **Annotate one tree with values from different variables.** Using `subset` aesthetic mapping (as in TREE1 panel) or `td_filter()` (as in TREE2 panel) to filter variables to be displayed on the specific panel.
```{r onetreefacet, warning=FALSE, fig.width=8, fig.height=4,fig.cap="(ref:onetreefacetcap)", fig.scap="(ref:onetreefacetscap)", out.width='100%'}
set.seed(2020)
x <- rtree(30)
d <- data.frame(label=x$tip.label, var1=abs(rnorm(30)), var2=abs(rnorm(30)))
tree <- full_join(x, d, by='label')
trs <- list(TREE1 = tree, TREE2 = tree)
class(trs) <- 'treedataList'
ggtree(trs) + facet_wrap(~.id) +
geom_tippoint(aes(subset=.id == 'TREE1', colour=var1)) +
scale_colour_gradient(low='blue', high='red') +
ggnewscale::new_scale_colour() +
geom_tippoint(aes(colour=var2), data=td_filter(.id == "TREE2")) +
scale_colour_viridis_c()
```
### DensiTree {#densitree}
Another way to view the bootstrap trees is to merge them to form a density tree using `ggdensitree()` function (Figure \@ref(fig:densiTree)). This will help us to identify consensus and differences among a large set of trees. The trees will be stacked on top of each other and the structures of the trees will be rotated to ensure the consistency of the tip order. The tip order is determined by the `tip.order` parameter and by default (`tip.order = 'mode'`) the tips are ordered by the most commonly seen topology. The user can pass in a character vector to specify the tip order, or pass in an integer, N, to order the tips by the order of the tips in the Nth tree. Passing `mds` to `tip.order` will order the tips based on MDS (Multidimensional Scaling) of the path length between the tips, or passing `mds_dist` will order the tips based on MDS of the distance between the tips.
(ref:densiTreescap) DensiTree.
(ref:densiTreecap) **DensiTree.** Trees are stacked on top of each other and the structures of the trees are rotated to ensure the consistency of the tip order.
```{r densiTree, fig.width=12, fig.height=7.5, fig.cap="(ref:densiTreecap)", fig.scap="(ref:densiTreescap)", out.width='100%'}
ggdensitree(btrees, alpha=.3, colour='steelblue') +
geom_tiplab(size=3) + hexpand(.35)
```
## Summary {#summary4}
Visualizing phylogenetic trees with `r Biocpkg("ggtree")` is easy by using a single command `ggtree(tree)`. The `r Biocpkg("ggtree")` package provides several geometric layers to display tree components such as tip labels, symbolic points for both external and internal nodes, root-edge, *etc*. Associated data can be used to rescale branch lengths, color the tree, and be displayed on the tree. All these can be done by the `r CRANpkg("ggplot2")` grammar of graphic syntax, which makes it very easy to overlay layers and customize the tree graph (via `r CRANpkg("ggplot2")` themes and scales). The `r Biocpkg("ggtree")` package also provides several layers that are specifically designed for tree annotation which will be introduced in [Chapter 5](#chapter5). The `r Biocpkg("ggtree")` package makes the presentation of trees and associated data extremely easy. Simple graphs are easy to generate, while complex graphs are simply superimposed layers and are also easy to generate.