Tuesday, May 17, 2011

A simple function for plotting phylogenies in ggplot2

UPDATE: Greg jordan has a much more elegant way of plotting trees with ggplot2. See his links in the comments below.


I wrote a simple function for plotting a phylogeny in ggplot2. However, it only handles a 3 species tree right now, as I haven't figured out how to generalize the approach to N species.

Any ideas on how to improve this?



###### Simple function for plotting phylogenies in ggplot2
# x = a phylo object
# form = one of: star or ladder
# dependencies: ape, ggplot2, adephylo (loaded within function)
ggtree <- function(x, form) {
# Load packages
require(ape); require(ggplot2); require(adephylo)
# Define plotting format
phytheme_ <- function()
list(theme_bw(),
opts(panel.grid.major = theme_blank(), panel.grid.minor = theme_blank(),
legend.position="none", axis.text.x = NULL, axis.text.y = NULL,
axis.ticks = NULL, panel.border = NULL),
labs(x = "", y = ""))
# Process newick file
tree_ <- as(as(x, "phylo4"), "data.frame") # convert to phylo4 table
tree_tips <- tree_[tree_$node.type == "tip", ] # get table with tips only
ntips <- nrow(tree_tips) # get number of tips
# Plot tree
if ( form == "ladder" ) {
t_ <- ggplot(tree_) +
geom_segment(aes(x = 1, y = 1, xend = 1-tree_[1,4], yend = 1)) + # tip
geom_segment(aes(x = 1, y = 2, xend = 1-tree_[2,4], yend = 2)) + # tip
geom_segment(aes(x = 1, y = 3, xend = 1-tree_[3,4], yend = 3)) + # tip
geom_segment(aes(x = 1-tree_[1,4], y = 1.5, xend = 1-tree_[1,4]-tree_[5,4], yend = 1.5)) +
geom_segment(aes(x = 1-tree_[1,4], y = 1, xend = 1-tree_[1,4], yend = 2)) +
geom_segment(aes(x = 1-tree_[3,4], y = 1.5, xend = 1-tree_[3,4], yend = 3)) +
geom_text(data = tree_tips, aes(x = 1, y = node, label = label, hjust = 0)) + # label tips
phytheme_() # add theme options
return(t_) } else # return tree
if ( form == "star" ) {
tree_tips_ <- cbind(tree_tips, star = seq(0, 1, 0.5)) # add column of star end locations
star_t_ <- ggplot(tree_tips_) +
geom_segment(aes(x = 0, y = 0.5, xend = 1, yend = tree_tips_[1,6])) + # tip
geom_segment(aes(x = 0, y = 0.5, xend = 1, yend = tree_tips_[2,6])) + # tip
geom_segment(aes(x = 0, y = 0.5, xend = 1, yend = tree_tips_[3,6])) + # tip
geom_text(aes(x = 1, y = star, label = label, hjust = 0)) + # label tips
phytheme_() # add theme options
return(star_t_) } # return tree
}
###### Example
tree <- rcoal(3)
ggtree(tree, "star")
ggtree(tree, "ladder")
view raw ggtree_v1.R hosted with ❤ by GitHub

1 comment:

  1. I implemented a ggplot-based tree plot function for the phylosim package: http://cran.r-project.org/web/packages/phylosim/vignettes/PhyloSim.pdf

    The examples don't show off the tree plotting so much, but here's an example of a plot that colors and scales lines using NHX annotations: http://www.ebi.ac.uk/~greg/scratch/NKX2-3_plot_tree.pdf

    Right now the plotting functions aren't too well documented, but feel free to get in touch if you'd like to see more.

    ReplyDelete