Friday, October 18, 2019

Growing a birth-death phylogeny from left to right & then converting it to an animated .gif in R

In response to a recent tweet by Jeet Sukumaran:

the following is code to 'grow' a birth-death tree from left to right.

The code stores the individual frames as .png files & then combines them together by calling the software ImageMagick, which must be installed & (in Windows) added to the System Environment Path for the code to work as intended. Note that file.remove(list.files(pattern=".png")) will clear all the .png files from your current working directory - so use with caution.

## load library
library(phytools)
## set simulation conditions
t<-100
b<-0.06
d<-0.02
## simulation B-D tree
tree<-pbtree(b=b,d=d,t=t)
## create animated plot:
h<-max(nodeHeights(tree))
png(file="pbtree-%03d.png",width=1000,height=600,res=144)
for(i in 1:100){
    dev.hold()
    if(i<100){ 
        tt<-make.era.map(tree,c(0,i*h/100))
        plot(tt,colors=setNames(c('blue','transparent'),1:2),
            ftype="off",lwd=2,direction="leftwards",
            xlim=c(t,0),
            mar=c(4.1,1.1,1.1,1.1))
    } else { 
        tt<-paintSubTree(tree,Ntip(tree)+1,"1","2")
        tt$mapped.edge<-cbind(tt$mapped.edge,
            rep(0,nrow(tt$mapped.edge)))
        plot(tt,colors=setNames('blue',1),
            ftype="off",lwd=2,direction="leftwards",
            xlim=c(t,0),
            mar=c(4.1,1.1,1.1,1.1))
    }
    axis(1)
    title(xlab="time before present")
    dev.flush()
}
dev.off()
## png 
##   2
system("ImageMagick convert -delay 10 -loop 0 *.png pbtree-anim.gif")
## [1] 0
file.remove(list.files(pattern=".png"))
##   [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
##  [15] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
##  [29] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
##  [43] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
##  [57] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
##  [71] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
##  [85] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE
##  [99] TRUE TRUE

Cool!

No comments:

Post a Comment

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