Search code examples
rphylogeny

Plot squares close to phylogeny taxa


I am trying to plot some coloured squares next to the terminal nodes of a phylogeny. However, I can't get the squares close to the terminal nodes. I think this is something to do with the taxa labels - despite having them turned off.

I plan to plot columns of squares after each other, which is why I can't use tip.labels with square characters.

here is my test function:

.squares = function(colour, start_point, n){
    colour = colour[length(colour):1]

    inc = 200
    ## Plot either points or rectangles. Dependant on arugment
    rect(start_point, 0.5:(n-0.5), start_point+inc, 
         1.5:(n+0.5), col = colour)
    start_point = start_point + inc ## inc is the width of each box. 
    start_point
}

And here is the test code:

library(ape)

n = 20
tree = rcoal(n, tip.label = letters[1:n])
t = plot(tree, show.tip.label = FALSE, no.margin = TRUE)

abline(v = t$x.lim[2], col = "red", lwd = 5)
.squares(rep("red", 20), start_point = t$x.lim[2], n = n)

Which gives:

enter image description here

I can't figure out how to close the gap between the squares and the terminal nodes.

Any direction would be appreciated. Since I will also be plotting multiple columns of squares, It would be helpful to know how I could add more columns without going into the margins.

thanks


Solution

  • I can't seem to reproduce your bug either (the horizontal line is added properly at the tips limit).

    However, your problem seems really similar to posts on Liam Revell's excellent blog. Have a look at this code, that one or even better, this final one.

    In your case, you could use something like that:

    ## phytools package
    library(phytools)
    
    ## The tree
    n = 20
    tree = rcoal(n, tip.label = letters[1:n])
    
    ## The data
    data <- data.frame(rep(1, n), rep(2, n))
    colnames(data) <- c("Something", "SomethingElse")
    
    ## The plot (using a near 0 font size plot)
    object <- plotTree.datamatrix(tree, data, sep=0, srt=70, yexp=1.05, fsize=0.0001)