Saturday, March 18, 2017

Hack to offset tip labels in plotted fan tree

Yesterday I received the following inquiry about phytools:

“I am using your package to create stochastic character maps in R and I have not had any luck offsetting the species names when creating my fan trees. Do you have any suggestions about how this can be fixed, it would be greatly appreciated.”

In fact, label offset is not an option in plot.simmap(...,type="fan"); however the following is a fairly elegant hack I thought of this morning:

library(phytools)
library(geiger)
data(anoletree) ## our tree that we will use for this example
anoletree
## 
## Phylogenetic tree with 82 tips and 81 internal nodes.
## 
## Tip labels:
##  Anolis_ahli, Anolis_allogus, Anolis_rubribarbus, Anolis_imias, Anolis_sagrei, Anolis_bremeri, ...
## 
## The tree includes a mapped, 6-state discrete character with states:
##  CG, GB, TC, TG, Tr, Tw
## 
## Rooted; includes branch lengths.
## first plot the tree with transparent color:
h<-max(nodeHeights(anoletree))
offset.factor<-1.05 ## increase this for greater offset
plotTree(rescale(anoletree,model="depth",depth=offset.factor*h),
    color="transparent",ftype="i",type="fan",fsize=0.7,lwd=3)
par(fg="transparent")
obj<-get("last_plot.phylo",envir=.PlotPhyloEnv)
plot(anoletree,type="fan",fsize=0.7,ftype="i",add=TRUE,
    xlim=obj$x.lim,ylim=obj$y.lim,lwd=3)
## no colors provided. using the following legend:
##        CG        GB        TC        TG        Tr        Tw 
##   "black"     "red"  "green3"    "blue"    "cyan" "magenta"
par(fg="black")
## add a legend
states<-sort(unique(getStates(anoletree,"tips")))
add.simmap.legend(x=obj$x.lim[1],y=obj$y.lim[2],
    colors=setNames(palette()[1:length(states)],states),
    prompt=FALSE)

plot of chunk unnamed-chunk-1

That's the hack.

2 comments:

  1. Liam, this hack is awesome, really makes the plot more clear. For some reason when I add in the simmap legend, I'm only getting squares with the correct colors, but no text. When I plot the tree and the legend normally it works just fine. Any thoughts on what might be happening? Thanks.

    ReplyDelete
    Replies
    1. Yes. You probably didn't set:

      par(fg="black")

      before adding the legend. - Liam

      Delete