There are many software packages and webtools that are designed for displaying phylogenetic trees, such as TreeView (Page 2002), FigTree, TreeDyn (Chevenet et al. 2006), Dendroscope (Huson and Scornavacca 2012), EvolView (He et al. 2016) and iTOL (Letunic and Bork 2007), etc.. Only several of them, such as FigTree, TreeDyn and 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 the phylogenetic covariates and other associated data from different sources into the trees for visualizations and further analyses. For instance, influenza virus has a wide host range, diverse and dynamic genotypes and characteristic transmission behaviors that are mostly associated with the virus evolution and essentially among themselves. Therefore, in addition to standalone applications that focus on each of the specific analysis and data type, 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 ggtree (Yu et al. 2017), a package for the R programming language (R Core Team 2016) released under the Bioconductor project (Gentleman et al. 2004). The ggtree is built to work with tree data object (see chapter 1 and chapter 9), and display tree graphics with ggplot2 package (Wickham 2016) that was based on the grammar of graphics (Wilkinson et al. 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 ape (Paradis, Claude, and Strimmer 2004) and phytools (Revell 2012), which are capable of displaying and annotating trees, are developed using the base graphics system of R. In particular, ape is one of the fundamental package for phylogenetic analysis and data processing. However, the base graphics system is relatively difficult to extend and limits the complexity of tree figure to be displayed. OutbreakTools (Jombart et al. 2014) and phyloseq (McMurdie and Holmes 2013) extended ggplot2 to plot phylogenetic trees. The 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 and annotation. The ggtree package also inherits versatile properties of ggplot2, and more importantly allows constructing complex tree figures by freely combining multiple layers of annotations (see also Chapter 5) using the tree associated data imported from different sources (see detailed in Chapter 1 and (Wang et al. 2020)).
The ggtree package (Yu et al. 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, 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 et al. 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 et al. 2012).
The ggtree supports ggplot2’s graphical language, which allows high level of customization, is intuitive and flexible. It is notable that ggplot2 itself does not provide low-level geometric objects or other support for tree-like structures, and hence ggtree is a useful extension on that regard. Even though the other two phylogenetics-related R packages, OutbreakTools and phyloseq, are developed based on ggplot2, the most valuable part of ggplot2 syntax - adding layers of annotations - is not supported in these packages. For example, if we have plotted a tree without taxa labels, OutbreakTools and 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 ggtree extends ggplot2 to support tree objects by implementing a geometric layer,
geom_tree(), to support visualizing tree structure. In 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, 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_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 ggtree are summarized in Table 5.1.
To view a phylogenetic tree, we first need to parse the tree file into
The treeio package is able to parse diverse annotation data from different software outputs into
S4 phylogenetic data objects (see also [Chapter 1]](#chapter1)). The ggtree package mainly utilizes these
S4 objects to display and annotate the tree. There are also other R packages that defined
S4 classes to store phylogenetic trees with domain specific associated data, including
phylo4d defined in phylobase package,
obkdata defined in OutbreakTools package, and
phyloseq defined in phyloseq package etc. (see also Chapter 9). All these tree objects are also supported in ggtree and their specific annotation data can be used to annotate the tree directly in ggtree. Such compatibility of ggtree facilitates the integration of data and analysis results. In addition, ggtree also supports other tree-like structure, including dendrogram.
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()
ggtree(), was implemented as a short cut to visualize a tree, and it works exactly the same as shown above.
ggtree(tree, color="firebrick", size=2, linetype="dotted")
branch.length is used to scale the edge, user can set the parameter
branch.length = "none" to only view the tree topology (cladogram, Figure 4.1D) or other numerical variable to scale the tree (e.g. dN/dS, see also in Chapter 5).
Viewing phylogenetic with ggtree is quite simple, just pass the tree object to the
ggtree() function. We have developed several types of layouts for tree presentation (Figure 4.2), including rectangular (by default), slanted, circular, fan, unrooted (equal angle and daylight methods), time-scaled and 2-dimensional layouts.
Here are examples of visualizing a tree with different layouts:
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')
There are also other possible layouts that can be drawn by modifying scales/coordination (Figure 4.3).
ggtree(tree) + scale_x_reverse() ggtree(tree) + coord_flip() ggtree(tree) + layout_dendrogram() ggplotify::as.ggplot(ggtree(x), 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)
Phylogram. Layouts of rectangular, roundrect, slanted, ellipse, circular and fan are supported to visualize phylogram (by default, with branch length scaled) as demonstrated in Figure 4.2A-F.
Unrooted layout. Unrooted (also called ‘radial’) layout is supported by equal-angle and daylight algorithms, user can specify unrooted layout algorithm by passing “equal_angle” or “daylight” to
layout parameter to visualize the tree. Equal-angle method was proposed by Christopher Meacham in PLOTREE, which was incorporated in PHYLIP (Retief 2000). This method starts from the root of the tree and allocates arcs of angle to each subtrees 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 4.2G, equal angle method has a drawback that tips are tend to be clustered together and leaving 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 4.2H). This method was firstly implemented in PAUP* (Wilgenbusch and Swofford 2003).
Cladogram. To visualize cladogram that without branch length scaling and only display the tree structure,
branch.length is set to “none” and it works for all types of layouts (Figure 4.2I-L).
Time-scaled layout. For time-scaled tree, the most recent sampling date must be specified via the
mrsd parameter and ggtree will scaled the tree by sampling (tip) and divergence (internal node) time, and a time scale axis will be displayed under the tree by default.
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 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 is a new layout we proposed in ggtree, which 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 influenza virus evolution (Neher et al. 2016), though such analysis diagrams are not tree-like, i.e., no connection between data points, unlike our two-dimensional tree layout that connect 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 4.4; data published in (Liang et al. 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. To scaled 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
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 <- get.tree(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 4.5, two-dimensional tree good at visualizing the change of phenotype over the evolution in the phylogenetic tree. In this example, it is shown that H3 gene of human influenza A virus maintained high level of N-linked glycosylation sites (n=8 to 9) over 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 high level of glycosylation on the viral hemagglutinin protein provides better shielding effect to protect the antigenic sites from exposure to the herd immunity, and thus has selective advantage in human populations that maintain 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 swine population, the shielding effect of the high-level surface glycan oppositely impose selective disadvantage because the receptor-binding domain may also be shielded which greatly affect the viral fitness of the lineage that newly adapted to a new host species. Another example of two-dimensional tree can be found on Figure 4.12.
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
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.
p <- ggtree(tree) + geom_nodepoint(color="#b5e521", alpha=1/4, size=10) p + geom_tippoint(color="#FDAC4F", shape=8, size=3)
p + geom_tiplab(size=3, color="purple")
geom_tiplab() layer not only supports using text or label geom to display labels,
it also supports image geom to label tip with image files (see Chapter 7). A corresponding
geom_nodelab() is also provided for displaying node labels.
For long tip labels, the label maybe truncated. There are several ways to solve this issue (see FAQ: Tip label truncated).
Another solution to solve this issue is to display tip labels as y-axis labels (Figure 4.8C). However it only works for rectangular and dendrogram layouts and users need to use
theme() to adjust tip labels in this case.
By default, the positions to display text are based on the node positions, we can change them to based on the middle of the branch/edge (by setting
aes(x = branch)), which is very useful when annotating transition from parent node to child node.
The ggtree doesn’t plot root edge by default. Users can use
geom_rootedge() to automatically display root edge (Figure 4.9A). If there is no root edge information,
geom_rootedge() will display nothing by default (Figure 4.9B). Users can set the root edge to the tree (Figure 4.9C) or specify
geom_rootedge() (Figure 4.9D). A long root length is useful to increase readibility of the circular tree (see also FAQ: Enlarge center space).
## 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 length of root edge for just plotting ## this will ignore tree$root.edge ggtree(tree2) + geom_tiplab() + geom_rootedge(rootedge = 3)
User can use any feature (if available), including clade posterior and dN/dS etc., to scale the color of the tree. If the feature is continuous numerical value, ggtree provides a
continuous parameter to support plotting continuous state transition in edges. Here, we use the example provided in http://www.phytools.org/eqg2015/asr.html to demonstrate this functionality. 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 4.11B.
anole.tree<-read.tree("http://www.phytools.org/eqg2015/data/anole.tre") svl <- read.csv("http://www.phytools.org/eqg2015/data/svl.csv", row.names=1) svl <- as.matrix(svl)[,1] fit <- phytools::fastAnc(anole.tree,svl,vars=TRUE,CI=TRUE) td <- data.frame(node = nodeid(anole.tree, 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(anole.tree, d, by = 'node') p1 <- ggtree(tree, aes(color=trait), layout = 'circular', ladderize = FALSE, continuous = TRUE, 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=T, 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)) cowplot::plot_grid(p1, p2, ncol=2, labels=c("A", "B"))
Besides, we can use two-dimensional tree (as demonstrated in Figure 4.5) to visualize phenotype on the vertical dimension to create the phenogram. We can use ggrepel package to repel tip labels to avoid overlapping as demonstrated in Figure A.4.
Most of the phylogenetic trees are scaled by evolutionary distance (substitution/site). In ggtree, users can re-scale a phylogenetic tree by any numerical variable inferred by evolutionary analysis (e.g. dN/dS).
library("treeio") beast_file <- system.file("examples/MCC_FluA_H3.tree", package="ggtree") beast_tree <- read.beast(beast_file) beast_tree
## 'treedata' S4 object that stored information of ## '/home/ygc/R/library/ggtree/examples/MCC_FluA_H3.tree'. ## ## ...@ phylo: ## Phylogenetic tree with 76 tips and 75 internal nodes. ## ## Tip labels: ## A/Hokkaido/30-1-a/2013, A/New_York/334/2004, A/New_York/463/2005, A/New_York/452/1999, A/New_York/238/2005, A/New_York/523/1998, ... ## ## Rooted; includes branch lengths. ## ## with the following features available: ## 'height', 'height_0.95_HPD', 'height_median', ## 'height_range', 'length', 'length_0.95_HPD', ## 'length_median', 'length_range', 'posterior', 'rate', ## 'rate_0.95_HPD', 'rate_median', 'rate_range'.
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")
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")
In addition to specify
branch.length in tree visualization, users can change branch length stored in tree object by using
rescale_tree() function provided by the treeio package (Wang et al. 2020), and the following command will display a tree that is identical to (Figure 4.13B). The
rescale_tree() function was documented in session 2.4.
theme_tree() defined a totally blank canvas, while
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 to the
theme_tree2() functions to modify them.
set.seed(2019) x <- rtree(30) ggtree(x, color="red") + theme_tree("steelblue") ggtree(x, color="white") + theme_tree("black")
Users can also use image file as tree background, see example in Appendix B.
The ggtree supports
treedataList objects and a list of trees can be viewed simultaneously.
## trees <- lapply(c(10, 20, 40), rtree) ## class(trees) <- "multiPhylo" ## ggtree(trees) + facet_wrap(~.id, scale="free") + geom_tiplab() r8s <- read.r8s(system.file("extdata/r8s", "H3_r8s_output.log", package="treeio")) ggtree(r8s) + facet_wrap( ~.id, scale="free") + theme_tree2()
One hundred bootstrap trees can also be view simultaneously.
btrees <- read.tree(system.file("extdata/RAxML", "RAxML_bootstrap.H3", package="treeio")) ggtree(btrees) + facet_wrap(~.id, ncol=10)
Another solution is to utilize the ability of plotting a list of tree by ggtree, and then add annotation layers for selected variable at specific panel via the subset aesthetic mapping supported by ggtree or using td_filter() as demonstrated in Figure 4.17.
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()
Visualizing phylogenetic tree using ggtree is easy by using a single command
ggtree(tree). The 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 display on the tree. All these can be done by the ggplot2 grammar of graphic syntax. ggtree also provides several layers that are specifically designed for tree annotation (see Chapter 5).