Friday, June 2, 2017

Custom tip-spacing of a fan tree plot in R

Today I received the following query (flattering commentary included on purpose - thank you for saying so!):

“I'm a big fan (pun intended) of all of your wonderful work creating customizable, interpretable, functional, phylogenetic plots in R (as well as the invaluable analytical advice you are so generous with). I am writing to ask if you know of any way(s) to modify the spacing of specific clades in a radial plot. Specifically, something that might allow users define the "fraction, θ, of the circle we want to use” (your original description) for specific clades? For what it's worth, I want to 'scrunch-up' certain clades and expand others, for the purposes of better illustrating certain phenotypic characters and their phylogenetic distributions. Any input or advice would be much appreciated!“

This is indeed something we can do with the argument tips, which exists specifically to permit custom tip spacing of different clades in phytools.

For instance, first our original tree:

library(phytools)
tree
## 
## Phylogenetic tree with 100 tips and 99 internal nodes.
## 
## Tip labels:
##  t91, t92, t16, t85, t86, t56, ...
## 
## Rooted; includes branch lengths.
plotTree(tree,type="fan",ftype="off")
labelnodes(1:Ntip(tree)+tree$Nnode,1:Ntip(tree)+tree$Nnode,
    interactive=FALSE,cex=0.8)

plot of chunk unnamed-chunk-1

Now, let's imagine we want to relatively expand the space occupied by the clades descended from nodes 102, 130, & 169. We can do so as follows:

cw<-reorder(tree)
tips<-setNames(rep(1,Ntip(tree)),cw$tip.label)
nodes<-c(102,130,169)
get.tips<-function(node,tree){
    dd<-getDescendants(tree,node)
    tree$tip.label[dd[dd<=Ntip(tree)]]
}
desc<-unlist(lapply(nodes,get.tips,tree=cw))
for(i in 2:Ntip(cw))
    tips[i]<-tips[i-1]+
        if(names(tips)[i]%in%desc){
            1 
        } else if(names(tips)[i-1]%in%desc){ 
            1 
        } else 0.2
plotTree(tree,tips=tips,ftype="off",type="fan")
labelnodes(1:Ntip(tree)+tree$Nnode,1:Ntip(tree)+tree$Nnode,
    interactive=FALSE,cex=0.8)

plot of chunk unnamed-chunk-2

Here, I'll paint each of these subtrees so that the differences is evident:

cw<-paintSubTree(cw,102,"2")
cw<-paintSubTree(cw,130,"2")
cw<-paintSubTree(cw,169,"2")
plot(cw,colors=setNames(c("blue","red"),1:2),lwd=4,type="fan",
    tips=tips,ftype="off")

plot of chunk unnamed-chunk-3

Cool. I think that is the general idea.

No comments:

Post a Comment

Note: due to the very large amount of spam, all comments are now automatically submitted for moderation.