Edge coloring with user data

December 11, 2016
By

(This article was first published on R on Guangchuang YU, and kindly contributed to R-bloggers)

Coloring edges in ggtree is quite easy, as we can map the color to numerical or categorical values via the aes(color=VAR) syntax. For user’s own data, it is also easy as ggtree provide the %<+% operator to attach user data.

But as it seems not so obviously for ggtree users, see question 1, 2, and 3, I will demonstrate how to color edges using user data here.

There are several solutions to this question. Let’s first start with a hard one by using phylo4d class defined by phylobase package:

require(ggtree)
require(phylobase)

set.seed(123)
tr = rtree(30)
g1 = as(tr, 'phylo4')
d = data.frame(color=sample(c('red', 'blue', 'green'), 30, replace=T))
rownames(d) = tr$tip.label
g2 = phylo4d(g1, d)

rNodeData <- data.frame(randomTrait = rnorm(nNodes(g1)),
                        color = sample(c('purple', 'yellow', 'black'), nNodes(g1), replace=T),
                        row.names = nodeId(g1, "internal"))

nodeData(g2) <- rNodeData

We can store the information in a phylo4d object and as this object is supported by ggtree. We can directly coloring the tree by mapping the color to specific variable.

ggtree(g2, aes(color=I(color)))

ggtree itself also provide solution by using the operator, %<+% to attach user data. After attaching, we can re-scale edge color by aes.

d = data.frame(node=1:59, color=sample(c('red', 'blue', 'green'), 59, replace=T))
ggtree(tr) %<+% d + aes(color=I(color))

To leave a comment for the author, please follow the link and comment on their blog: R on Guangchuang YU.

R-bloggers.com offers daily e-mail updates about R news and tutorials on topics such as: Data science, Big Data, R jobs, visualization (ggplot2, Boxplots, maps, animation), programming (RStudio, Sweave, LaTeX, SQL, Eclipse, git, hadoop, Web Scraping) statistics (regression, PCA, time series, trading) and more...



If you got this far, why not subscribe for updates from the site? Choose your flavor: e-mail, twitter, RSS, or facebook...

Comments are closed.

Search R-bloggers


Sponsors

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)