How can I plot a tree (and squirrels) in R?

后端 未结 5 1017
悲&欢浪女
悲&欢浪女 2020-12-24 06:32

Here is my tree:

tree = data.frame(branchID = c(1,11,12,111,112,1121,1122), length = c(32, 21, 19, 5, 12, 6, 2))

> tree
  branchID length
1        1              


        
5条回答
  •  离开以前
    2020-12-24 07:05

    Well, you could convert your data to define a "tree" as defined by the ape package. Here's a function that can convert your data.frame to the correct format.

    library(ape)
    
    to.tree <- function(dd) {
        dd$parent <- dd$branchID %/% 10
    
        root <- subset(dd, parent==0)
        dd <- subset(dd, parent!=0)
    
        ids <- unique(c(dd$parent, dd$branchID))
        tip <- !(ids %in% dd$parent)
        lvl <- ids[order(!tip, ids)]
        edg <- sapply(dd[,c("parent","branchID")], 
            function(x) as.numeric(factor(x, levels=lvl)))
    
        x<-list(
            edge=edg,
            edge.length=dd$length,
            tip.label=head(lvl, sum(tip)),
            node.label=tail(lvl, length(tip)-sum(tip)),
            Nnode = length(tip)-sum(tip),
            root.edge=root$length[1]
        )
        class(x)<-"phylo"
        reorder(x)    
    }
    

    Then we can plot it somewhat easily

    xx <- to.tree(tree)
    plot(xx, show.node.label=TRUE, root.edge=TRUE)
    

    Now, if we want to add the squirrel information, we need to know where each branch is located. I'm going to borrow getphylo_x and getphylo_y from this answer. Then I can run

    sx<-Vectorize(getphylo_x, "node")(xx, as.character(squirrels$branchID)) -
        tree$length[match(squirrels$branchID, tree$branchID)] +
        squirrels$PositionOnBranch
    sy<-Vectorize(getphylo_y, "node")(xx, as.character(squirrels$branchID))
    
    points(sx,sy)
    text(sx,sy, squirrels$name, pos=3)
    

    to add the squirrel information to the plot. The final result is

    enter image description here

    It's not perfect but it's not a bad start.

提交回复
热议问题