rtreeapeggtree

Keeping information of nodes after dropping tips


When I have a tree and some node information stored in a table, I would like to drop tips, and modify the table accordingly. So a new table with the correct new number in column node is necessary.

library(ape)
library(ggtree)
#make tree
set.seed(2016-12-31)
newrtree<-rtree(12)
newrtreepo<-di2multi(newrtree, tol = 0.5)

# make table with data to plot in tree
a<-1:newrtreepo$Nnode # node label
b<-seq(0,1, length.out=newrtreepo$Nnode)
c<-1-b
dat <- data.frame(a=a, b=b,c=c)
splen<-length(newrtreepo$tip.label)
dat$node <- splen+1:newrtreepo$Nnode
dat
#   a         b         c node
# 1 1 0.0000000 1.0000000   13
# 2 2 0.1428571 0.8571429   14
# 3 3 0.2857143 0.7142857   15
# 4 4 0.4285714 0.5714286   16
# 5 5 0.5714286 0.4285714   17
# 6 6 0.7142857 0.2857143   18
# 7 7 0.8571429 0.1428571   19
# 8 8 1.0000000 0.0000000   20

tree5<-ggtree(newrtreepo)+geom_tiplab()+
  geom_text2(aes(subset=!isTip, label=node), hjust=-1, check_overlap = T)+
  geom_text2(aes(subset=!isTip,x=branch, label=label, size=2), vjust=-.5, hjust=0.5)

piesa <- nodepie(dat, cols=2:3)
inset(tree5, piesa)

droptree2<-drop.tip(newrtreepo,c("t12","t3","t5"))

enter image description here


Solution

  • I created node labels to use as index to modify the table.

    #modify as in
    newrtreepo$node.label<-paste0("n",1:newrtreepo$Nnode)
    newrtreepo$node.copy<-newrtreepo$node.label
    
    droptree2<-drop.tip(newrtreepo,c("t12","t3","t5"))
    droptree2$node.label
    # "n1" "n2" "n3" "n5" "n6" "n7"
    droptree2$node.copy
    # "n1" "n2" "n3" "n4" "n5" "n6" "n7" "n8"
    
    newdatb<-dat[which(droptree2$node.copy %in% droptree2$node.label ==T),]
    rowdat<-nrow(newdatb)
    newlength<-length(droptree2$tip.label)
    newdatb$node <- newlength+1:rowdat
    newdatb
    #   a         b         c node
    # 1 1 0.0000000 1.0000000   10
    # 2 2 0.1428571 0.8571429   11
    # 3 3 0.2857143 0.7142857   12
    # 5 5 0.5714286 0.4285714   13
    # 6 6 0.7142857 0.2857143   14
    # 7 7 0.8571429 0.1428571   15
    
    
    tree6<-ggtree(droptree2)+geom_tiplab()+  
      geom_text2(aes(subset=!isTip, label=node), hjust=-1, check_overlap = T)+
      geom_text2(aes(subset=!isTip,x=branch, label=label, size=2), vjust=-.5)
    
    #label as bootstrap
    tree2treedata<-treeio::as.treedata(droptree2, newdatb$a)
    tree7<-ggtree(tree2treedata)+ geom_label(aes(label=bootstrap)) + geom_tiplab()+
      geom_text2(aes(subset=!isTip, label=node), hjust=-1, check_overlap = T)
    
    #create pies of reduced tree
    piesb <- nodepie(newdatb, cols=2:3)#, alpha=.6)
    gridExtra::grid.arrange(inset(tree5, piesa),inset(tree6, piesb),inset(tree7,piesb, width=0.15, height=0.15,
                                                                          hjust=0.2),ncol=2)
    

    enter image description here