Modified from Stephen Turner’s Tutorial
ggtree is an R package that extends ggplot2 for visualizating and annotating phylogenetic trees with their covariates and other associated data. It is available from Bioconductor. Bioconductor is a project to provide tools for analyzing and annotating various kinds of genomic data. You can search and browse Bioconductor packages here.
Bioconductor packages usually have great documentation in the form of vignettes. Take a look at the landing page for ggtree – about halfway down the page under the “Documentation” heading there are multiple walkthrough tutorials directed to different applications and functionalities of ggtree, chock full of runnable examples and explanations.
Just like R packages from CRAN, you only need to install Bioconductor packages once, then load them every time you start a new R session. Load the tidyverse package first.
library(tidyverse)
library(ggtree)
library(treeio)
library(ggimage)
From the ggtree landing page take a look at the Tree Data Import vignette. There are many different software packages for creating phylogenetic trees from different types of data, and there are many formats for storing the resulting phylogenetic trees they produce.
Most tree viewer software (including R packages) focus on Newick and Nexus file formats, and other evolution analysis software might also contain supporting evidence within the file that are ready for annotating a phylogenetic tree. ggtree supports several file formats, including:
and software output from:
The ggtree package implement several parser functions, including:
Let’s first import our tree data. We’re going to work with a made-up phylogeny with 13 samples (“tips”). Download the tree_newick.nwk data by clicking here or using the link above. Let’s load the libraries you’ll need if you haven’t already, and then import the tree using read.tree(). Displaying the object itself really isn’t useful. The output just tells you a little bit about the tree itself.
tree <- read.tree("tree_newick.nwk")
Just like with ggplot2 we created a basic canvas with ggplot(…) and added layers with +geom_???(), we can do the same here. The ggtree package gives us a geom_tree() function. Because ggtree is built on top of ggplot2, you get ggplot2’s default gray theme with white lines. You can override this with a theme from the ggtree package.
Because you’ll almost always want to add a tree geom and remove the default background and axes, the ggtree() function is essentially a shortcut for ggplot(…) + geom_tree() + theme_tree().
# build a ggplot with a geom_tree
ggplot(tree) + geom_tree() + theme_tree()
# This is convenient shorthand
#ggtree(tree)
There’s also the treescale geom, which adds a scale bar, or alternatively, you can change the default ggtree() theme to theme_tree2(), which adds a scale on the x-axis. The horizontal dimension in this plot shows the amount of genetic change, and the branches and represent evolutionary lineages changing over time. The longer the branch in the horizonal dimension, the larger the amount of change, and the scale tells you this. The units of branch length are usually nucleotide substitutions per site – that is, the number of changes or substitutions divided by the length of the sequence (alternatively, it could represent the percent change, i.e., the number of changes per 100 bases). See this article for more. Link currently broken.
# add a scale
ggtree(tree) + geom_treescale()
# or add the entire scale to the x axis with theme_tree2()
ggtree(tree) + theme_tree2()
The default is to plot a phylogram, where the x-axis shows the genetic change / evolutionary distance. If you want to disable scaling and produce a cladogram instead, set the branch.length=“none” option inside the ggtree() call. See ?ggtree for more.
The units of branch length are usually nucleotide substitutions per site – that is, the number of changes or substitutions divided by the length of the sequence.
# disable scaling, produce a cladogram
ggtree(tree, branch.length="none")
The … option in the help for ?ggtree represents additional options that are further passed to ggplot(). You can use this to change aesthetics of the plot. Let’s draw a cladogram (no branch scaling) using thick blue dotted lines (note that I’m not mapping these aesthetics to features of the data with aes() – we’ll get to that later).
# change aesthetics
ggtree(tree, branch.length="none", color="blue", size=2, linetype=3)
# 1. Create a slanted phylogenetic tree
ggtree(tree, layout = 'slanted')
# 2. Create a circular tree
ggtree(tree, layout = 'circular')
# 3. Create a circular unscaled cladogram with thick red lines
ggtree(tree, layout = 'circular', branch.length = 'none', color = 'red', size = 3)
# Add additional layers
# create the basic plot
p <- ggtree(tree)
# add node points
p + geom_nodepoint()
# add tip points
p + geom_tippoint()
# Label the tips
p + geom_tiplab()
Create a tree with these characteristics: * tips labeled in purple * purple-colored diamond-shape tip points (hint: Google search “R point characters”) * large semitransparent yellow node points (hint: alpha=) * Add a title with + ggtitle(…)
ggtree(tree) +
geom_nodepoint(size = 3, color = "goldenrod", alpha = 0.5) +
geom_tippoint(size = 3, color = "purple", pch = 18) +
geom_tiplab(size = 5, color = "purple") +
ggtitle("Exercise 2 Tree")
The geom_tiplab() function adds some very rudimentary annotation. Let’s take annotation a bit further. See the tree annotation and advanced tree annotation vignettes for more. Links currently broken.
Before we can go further we need to understand how ggtree is handling the tree structure internally. Some of the functions in ggtree for annotating clades need a parameter specifying the internal node number. To get the internal node number, user can use geom_text to display it, where the label is an aesthetic mapping to the “node variable” stored inside the tree object (think of this like the continent variable inside the gapminder object). We also supply the hjust option so that the labels aren’t sitting right on top of the nodes. Read more about this process in the ggtree manipulation vignette. Link currently broken.
# Display internal node numbers
ggtree(tree) + geom_text(aes(label=node), hjust=-.3)
Another way to get the internal node number is using MRCA() function by providing a vector of taxa names (created using c(“taxon1”, “taxon2”)).. The function will return node number of input taxa’s most recent commond ancestor (MRCA). First, re-create the plot so you can choose which taxa you want to grab the MRCA from.
# Or use MRCA()
# recreate plot
ggtree(tree) + geom_tiplab()
Let’s grab the most recent common ancestor for taxa C+E, and taxa G+H. We can use MRCA() to get the internal node numbers. Go back to the node-labeled plot from before to confirm this.
MRCA(tree, ("C"), ("E"))
## [1] 17
MRCA(tree, ("G"), ("H"))
## [1] 21
We can use geom_cladelabel() to add another geom layer to annotate a selected clade with a bar indicating the clade with a corresponding label. You select the clades using the internal node number for the node that connects all the taxa in that clade. See the tree annotation vignette for more. Link currently broken.
Let’s annotate the clade with the most recent common ancestor between taxa C and E (internal node 17). Let’s make the annotation red. See ?geom_cladelabel help for more.
ggtree(tree) +
geom_cladelabel(node=17, label="Some random clade", color="red")
Let’s add back in the tip labels. Notice how now the clade label is too close to the tip labels. Let’s add an offset to adjust the position. You might have to fiddle with this number to get it looking right.
ggtree(tree) +
geom_tiplab() +
geom_cladelabel(node=17, label="Some random clade",
color="red2", offset=.8)
Now let’s add another label for the clade connecting taxa G and H (internal node 21).
ggtree(tree) +
geom_tiplab() +
geom_cladelabel(node=17, label="Some random clade",
color="red2", offset=.8) +
geom_cladelabel(node=21, label="A different clade",
color="blue", offset=.8)
Uh oh. Now we have two problems. First, the labels would look better if they were aligned. That’s simple. Pass align=TRUE to geom_cladelabel() (see ?geom_cladelabel help for more). But now, the labels are falling off the edge of the plot. That’s because geom_cladelabel() is just adding it this layer onto the end of the existing canvas that was originally layed out in the ggtree call. This default layout tried to optimize by plotting the entire tree over the entire region of the plot. Here’s how we’ll fix this.
First create the generic layout of the plot with ggtree(tree).
Add some tip labels.
Add each clade label.
Remember theme_tree2()? We used it way back to add a scale to the x-axis showing the genetic distance. This is the unit of the x-axis. We need to set the limits on the x-axis. Google around for something like “ggplot2 x axis limits” and you’ll wind up on this StackOverflow page that tells you exactly how to solve it – just add on a + xlim(…, …) layer. Here let’s extend out the axis a bit further to the right.
Finally, if we want, we can either comment out the theme_tree2() segment of the code, or we could just add another theme layer on top of the plot altogether, which will override the theme that was set before. theme_tree() doesn’t have the scale.
ggtree(tree) +
geom_tiplab() +
geom_cladelabel(node=17, label="Some random clade",
color="red2", offset=.8, align=TRUE) +
geom_cladelabel(node=21, label="A different clade",
color="blue", offset=.8, align=TRUE) +
theme_tree2() +
xlim(0, 70) +
theme_tree()
Alternatively, we could highlight the entire clade with geom_hilight(). See the help for options to tweak.
ggtree(tree) +
geom_tiplab() +
geom_hilight(node=17, fill="gold") +
geom_hilight(node=21, fill="purple")
Some evolutionary events (e.g. reassortment, horizontal gene transfer) can be visualized with some simple annotations on a tree. The geom_taxalink() layer draws straight or curved lines between any of two nodes in the tree, allow it to show evolutionary events by connecting taxa. Take a look at the tree annotation vignette and ?geom_taxalink for more.
ggtree(tree) +
geom_tiplab() +
geom_taxalink("E", "H", color="blue3") +
geom_taxalink("C", "G", color="orange2", curvature=-.9)
Produce the figure below.
Easiest: use MRCA(tree, tip=c(“taxon1”, “taxon2”)) for B/C and L/J separately.
Alternatively: use ggtree(tree) + geom_text(aes(label=node), hjust=-.3) to see what the node labels are on the plot. You might also add tip labels here too.
Draw the tree with ggtree(tree).
Add tip labels.
Highlight these clades with separate colors.
Add a clade label to the larger superclade (node=17) that we saw before that includes A, B, C, D, and E. You’ll probably need an offset to get this looking right.
Link taxa C to E, and G to J with a dashed gray line (hint: get the geom working first, then try changing the aesthetics. You’ll need linetype=2 somewhere in the geom_taxalink()).
Add a scale bar to the bottom by changing the theme.
Add a title.
Optionally, go back to the original ggtree(tree, …) call and change the layout to “circular”.
MRCA(tree, ("B"), ("C"))
## [1] 19
MRCA(tree, ("L"), ("J"))
## [1] 23
ggtree(tree) +
theme_tree2() +
geom_tiplab() +
geom_hilight(node=19, fill="blue3") +
geom_hilight(node=23, fill="orange2") +
geom_taxalink("C", "E", lty=2) +
geom_taxalink("G", "J", lty=2) +
geom_cladelabel(node=17, label="Superclade 17",
color="darkred", offset=.8) +
ggtitle("Exercise 3 Tree")
Let’s use a previously published dataset from this paper:
Liang et al. “Expansion of genotypic diversity and establishment of 2009 H1N1 pandemic-origin internal genes in pigs in China.” Journal of virology (2014): 88(18):10864-74.
This data was reanalyzed in the ggtree paper.
The subset of the data used here contains 76 H3 hemagglutinin gene sequences of a lineage containing both swine and human influenza A viruses. The sequence data set was re-analyzed by using BEAST (available at http://beast.bio.ed.ac.uk/). BEAST (Bayesian Evolutionary Analysis Sampling Trees) can give you rooted, time-measured phylogenies inferred using molecular clock models.
For this you’ll need the flu_tree_beast.tree output file from BEAST and the flu_aasequence.fasta FASTA file with the multiple sequence alignment. These are both available on the data downloads page. First let’s read in the tree with read.beast() (instead of the read.tree() we used before). Let’s add a scale bar with theme_tree2(). This gives you genetic distance. But, we have time measured here with molecular clock models. We’ve only estimated the relative time between branching events, so if we want to actually see dates on the x-axis, we need to supply the most recent sampling date to the ggtree() call. Do this by setting mrsd=“YYYY-MM-DD” inside ggtree().
Finally, let’s add some tip labels. We’ll want to right-align them, and by default the dotted line is a little too thick. Let’s reduce the linesize a bit. Now, some of the labels might be falling off the margin. Set the xlim to limit the axis to show between 1990 and 2020. You could get MRCAs and node numbers and do all the annotations that we did before the same way here.
# Read the data
tree <- read.beast("flu_tree_beast.tree")
# supply a most recent sampling date so you get the dates
# and add a scale bar
ggtree(tree, mrsd="2013-01-01") +
theme_tree2()
# Finally, add tip labels and adjust axis
ggtree(tree, mrsd="2013-01-01") +
theme_tree2() +
geom_tiplab(align=TRUE, linesize=.5) +
xlim(1990, 2020)
Finally, let’s look at ?msaplot. This puts the multiple sequence alignment and the tree side-by-side. The function takes a tree object (produced with ggtree()) and the path to the FASTA multiple sequence alignment. You can do it with the entire MSA, or you could restrict to just a window. Want something interesting-looking, but maybe not all that useful? Try changing the coordinate system of the plot itself by passing + coord_polar(theta=“y”) to the end of the command!
msaplot(p=ggtree(tree), fasta="flu_aasequence.fasta", window=c(150, 175))
ggtree will let you plot many trees at once, and you can facet them the normal ggplot2 way. Let’s generate 3 replicates each of 4 random trees with 10, 25, 50, and 100 tips, plotting them all.
set.seed(42)
trees <- lapply(rep(c(10, 25, 50, 100), 3), rtree)
class(trees) <- "multiPhylo"
ggtree(trees) + facet_wrap(~.id, scale="free", ncol=4) + ggtitle("Many trees. Such phylogenetics. Wow.")
For showing a phylogenetic tree alongside other panels with your own data, the facet_plot() function accepts a input data.frame and a geom function to draw the input data.
# Generate a random tree with 30 tips
tree <- rtree(30)
# Make the original plot
p <- ggtree(tree)
# generate some random values for each tip label in the data
d1 <- data.frame(id=tree$tip.label, val=rnorm(30, sd=3))
# Make a second plot with the original, naming the new plot "dot",
# using the data you just created, with a point geom.
p2 <- facet_plot(p, panel="dot", data=d1, geom=geom_point, aes(x=val), color='red3')
# Make some more data with another random value.
d2 <- data.frame(id=tree$tip.label, value = abs(rnorm(30, mean=100, sd=50)))
# Now add to that second plot, this time using the new d2 data above,
# This time showing a bar segment, size 3, colored blue.
p3 <- facet_plot(p2, panel='bar', data=d2, geom=geom_segment,
aes(x=0, xend=value, y=y, yend=y), size=3, color='blue4')
# Show all three plots with a scale
p3 + theme_tree2()
phylopic.org hosts free silhouette images of animals, plants, and other life forms, all under Creative Commons or Public Domain. You can use ggtree to overlay a phylopic image on your plot at a node of your choosing.
# get phylopic
newick <- "((Pongo_abelii,(Gorilla_gorilla_gorilla,(Pan_paniscus,Pan_troglodytes)Pan,Homo_sapiens)Homininae)Hominidae,Nomascus_leucogenys)Hominoidea;"
tree <- read.tree(text=newick)
d <- ggimage::phylopic_uid(tree$tip.label)
d$body_mass = c(52, 114, 47, 45, 58, 6)
p <- ggtree(tree) %<+% d +
geom_tiplab(aes(image=uid, colour=body_mass), geom="phylopic", offset=2.5) +
geom_tiplab(aes(label=label), offset = .2) + xlim(NA, 7) +
scale_color_viridis_c()
p
my_tree$tip.label
## [1] "Chlorobium_chlorochromatii" "Thermotoga_lettingae_"
## [3] "Trypanosoma_cruzi_nuclear" "Amphidinium_carterae"
## [5] "Saccharomyces_cerevisiae_nuclear" "Homo_sapies_nuclear"
## [7] "Drosophila_yakuba_nuclear" "Oryza_nuclear"
## [9] "Archaeoglobus_fulgidus" "Methanocaldococcus_jannaschii"
## [11] "Pyrococcus_abyssi" "Nanoarchaeum_equitans"
## [13] "Halalkalicoccus_jeotgali" "Thermoplasma_volcanium"
## [15] "Candidatus_Korarchaeum_cryptofilum_" "Prochlorococcus_marinus"
## [17] "Oryza_chloroplast" "Burkholderia_cenocepacia_"
## [19] "Escherichia_coli_" "Rhizobium_leguminosarum"
## [21] "Oryza_mitochondrion"
#Eukaryotes?
MRCA(my_tree, ("Drosophila_yakuba_nuclear"), ("Trypanosoma_cruzi_nuclear"))
## [1] 25
#Archaea?
MRCA(my_tree, ("Candidatus_Korarchaeum_cryptofilum_"), ("Nanoarchaeum_equitans"))
## [1] 30
#Bacteria?
MRCA(my_tree, ("Oryza_mitochondrion"), ("Prochlorococcus_marinus"))
## [1] 36
ggtree(my_tree) +
xlim(0,2) +
geom_tippoint(size = 2, pch = 18) +
geom_tiplab(size = 2.5) +
ggtitle("My Tree of Life (from CIPRES)")+
geom_hilight(node=25, fill="seagreen", extend = 0.5) +
geom_hilight(node=30, fill="palevioletred", extend = 0.5) +
geom_hilight(node=36, fill="royalblue1", extend = 0.5) +
geom_cladelabel(node=25, label="Eukaryotes", offset = .5) +
geom_cladelabel(node=30, label="Archaea", offset = .5) +
geom_cladelabel(node=36, label="Bacteria", offset = .5)