]> git.donarmstrong.com Git - ape.git/blob - R/plot.phylo.R
new option 'draw' in plot.phylo()
[ape.git] / R / plot.phylo.R
1 ## plot.phylo.R (2011-03-29)
2
3 ##   Plot Phylogenies
4
5 ## Copyright 2002-2011 Emmanuel Paradis
6
7 ## This file is part of the R-package `ape'.
8 ## See the file ../COPYING for licensing issues.
9
10 plot.phylo <-
11     function(x, type = "phylogram", use.edge.length = TRUE,
12              node.pos = NULL, show.tip.label = TRUE,
13              show.node.label = FALSE, edge.color = "black",
14              edge.width = 1, edge.lty = 1, font = 3, cex = par("cex"),
15              adj = NULL, srt = 0, no.margin = FALSE, root.edge = FALSE,
16              label.offset = 0, underscore = FALSE, x.lim = NULL,
17              y.lim = NULL, direction = "rightwards", lab4ut = "horizontal",
18              tip.color = "black", draw = TRUE, ...)
19 {
20     Ntip <- length(x$tip.label)
21     if (Ntip == 1) {
22         warning("found only one tip in the tree")
23         return(NULL)
24     }
25     if (any(tabulate(x$edge[, 1]) == 1))
26       stop("there are single (non-splitting) nodes in your tree; you may need to use collapse.singles()")
27
28     .nodeHeight <- function(Ntip, Nnode, edge, Nedge, yy)
29         .C("node_height", as.integer(Ntip), as.integer(Nnode),
30            as.integer(edge[, 1]), as.integer(edge[, 2]),
31            as.integer(Nedge), as.double(yy),
32            DUP = FALSE, PACKAGE = "ape")[[6]]
33
34     .nodeDepth <- function(Ntip, Nnode, edge, Nedge)
35         .C("node_depth", as.integer(Ntip), as.integer(Nnode),
36            as.integer(edge[, 1]), as.integer(edge[, 2]),
37            as.integer(Nedge), double(Ntip + Nnode),
38            DUP = FALSE, PACKAGE = "ape")[[6]]
39
40     .nodeDepthEdgelength <- function(Ntip, Nnode, edge, Nedge, edge.length)
41         .C("node_depth_edgelength", as.integer(Ntip),
42            as.integer(Nnode), as.integer(edge[, 1]),
43            as.integer(edge[, 2]), as.integer(Nedge),
44            as.double(edge.length), double(Ntip + Nnode),
45            DUP = FALSE, PACKAGE = "ape")[[7]]
46
47     Nedge <- dim(x$edge)[1]
48     Nnode <- x$Nnode
49     ROOT <- Ntip + 1
50     type <- match.arg(type, c("phylogram", "cladogram", "fan",
51                               "unrooted", "radial"))
52     direction <- match.arg(direction, c("rightwards", "leftwards",
53                                         "upwards", "downwards"))
54     if (is.null(x$edge.length)) use.edge.length <- FALSE
55
56     ## the order of the last two conditions is important:
57     if (type %in% c("unrooted", "radial") || !use.edge.length ||
58         is.null(x$root.edge) || !x$root.edge) root.edge <- FALSE
59     if (type == "fan" && root.edge) {
60         warning("drawing root edge with type = 'fan' is not yet supported")
61         root.edge <- FALSE
62     }
63
64     phyloORclado <- type %in% c("phylogram", "cladogram")
65     horizontal <- direction %in% c("rightwards", "leftwards")
66     xe <- x$edge # to save
67     if (phyloORclado) {
68         ## we first compute the y-coordinates of the tips.
69         phyOrder <- attr(x, "order")
70         ## make sure the tree is in cladewise order:
71         if (is.null(phyOrder) || phyOrder != "cladewise") {
72             x <- reorder(x) # fix from Klaus Schliep (2007-06-16)
73             if (!identical(x$edge, xe)) {
74                 ## modified from Li-San Wang's fix (2007-01-23):
75                 ereorder <- match(x$edge[, 2], xe[, 2])
76                 if (length(edge.color) > 1) {
77                     edge.color <- rep(edge.color, length.out = Nedge)
78                     edge.color <- edge.color[ereorder]
79                 }
80                 if (length(edge.width) > 1) {
81                     edge.width <- rep(edge.width, length.out = Nedge)
82                     edge.width <- edge.width[ereorder]
83                 }
84                 if (length(edge.lty) > 1) {
85                     edge.lty <- rep(edge.lty, length.out = Nedge)
86                     edge.lty <- edge.lty[ereorder]
87                 }
88             }
89         }
90 ### By contrats to ape (< 2.4), the arguments edge.color, etc., are
91 ### not elongated before being passed to segments(), except if needed
92 ### to be reordered
93         yy <- numeric(Ntip + Nnode)
94         TIPS <- x$edge[x$edge[, 2] <= Ntip, 2]
95         yy[TIPS] <- 1:Ntip
96     }
97     ## 'z' is the tree in pruningwise order used in calls to .C
98     z <- reorder(x, order = "pruningwise")
99 ###    edge.color <- rep(edge.color, length.out = Nedge)
100 ###    edge.width <- rep(edge.width, length.out = Nedge)
101 ###    edge.lty <- rep(edge.lty, length.out = Nedge)
102 ###    ## fix from Li-San Wang (2007-01-23):
103 ###    xe <- x$edge
104 ###    x <- reorder(x, order = "pruningwise")
105 ###    ereorder <- match(x$edge[, 2], xe[, 2])
106 ###    edge.color <- edge.color[ereorder]
107 ###    edge.width <- edge.width[ereorder]
108 ###    edge.lty <- edge.lty[ereorder]
109 ###    ## end of fix
110     if (phyloORclado) {
111         if (is.null(node.pos)) {
112             node.pos <- 1
113             if (type == "cladogram" && !use.edge.length) node.pos <- 2
114         }
115         if (node.pos == 1)
116             yy <- .nodeHeight(Ntip, Nnode, z$edge, Nedge, yy)
117         else {
118           ## node_height_clado requires the number of descendants
119           ## for each node, so we compute `xx' at the same time
120           ans <- .C("node_height_clado", as.integer(Ntip),
121                     as.integer(Nnode), as.integer(z$edge[, 1]),
122                     as.integer(z$edge[, 2]), as.integer(Nedge),
123                     double(Ntip + Nnode), as.double(yy),
124                     DUP = FALSE, PACKAGE = "ape")
125           xx <- ans[[6]] - 1
126           yy <- ans[[7]]
127         }
128         if (!use.edge.length) {
129             if (node.pos != 2) xx <- .nodeDepth(Ntip, Nnode, z$edge, Nedge) - 1
130             xx <- max(xx) - xx
131         } else  {
132             xx <- .nodeDepthEdgelength(Ntip, Nnode, z$edge, Nedge, z$edge.length)
133         }
134     } else switch(type, "fan" = {
135         ## if the tips are not in the same order in tip.label
136         ## and in edge[, 2], we must reorder the angles: we
137         ## use `xx' to store temporarily the angles
138         TIPS <- x$edge[which(x$edge[, 2] <= Ntip), 2]
139         xx <- seq(0, 2*pi*(1 - 1/Ntip), 2*pi/Ntip)
140         theta <- double(Ntip)
141         theta[TIPS] <- xx
142         theta <- c(theta, numeric(Nnode))
143         theta <- .nodeHeight(Ntip, Nnode, z$edge, Nedge, theta)
144         if (use.edge.length) {
145             r <- .nodeDepthEdgelength(Ntip, Nnode, z$edge, Nedge, z$edge.length)
146         } else {
147             r <- .nodeDepth(Ntip, Nnode, z$edge, Nedge)
148             r <- 1/r
149         }
150         xx <- r*cos(theta)
151         yy <- r*sin(theta)
152     }, "unrooted" = {
153         nb.sp <- .nodeDepth(Ntip, Nnode, z$edge, Nedge)
154         XY <- if (use.edge.length)
155             unrooted.xy(Ntip, Nnode, z$edge, z$edge.length, nb.sp)
156         else
157             unrooted.xy(Ntip, Nnode, z$edge, rep(1, Nedge), nb.sp)
158         ## rescale so that we have only positive values
159         xx <- XY$M[, 1] - min(XY$M[, 1])
160         yy <- XY$M[, 2] - min(XY$M[, 2])
161     }, "radial" = {
162         X <- .nodeDepth(Ntip, Nnode, z$edge, Nedge)
163         X[X == 1] <- 0
164         ## radius:
165         X <- 1 - X/Ntip
166         ## angle (1st compute the angles for the tips):
167         yy <- c((1:Ntip)*2*pi/Ntip, rep(0, Nnode))
168         Y <- .nodeHeight(Ntip, Nnode, z$edge, Nedge, yy)
169         xx <- X * cos(Y)
170         yy <- X * sin(Y)
171     })
172     if (phyloORclado) {
173         if (!horizontal) {
174             tmp <- yy
175             yy <- xx
176             xx <- tmp - min(tmp) + 1
177         }
178         if (root.edge) {
179             if (direction == "rightwards") xx <- xx + x$root.edge
180             if (direction == "upwards") yy <- yy + x$root.edge
181         }
182     }
183     if (no.margin) par(mai = rep(0, 4))
184     if (is.null(x.lim)) {
185         if (phyloORclado) {
186             if (horizontal) {
187                 x.lim <- c(0, NA)
188                 pin1 <- par("pin")[1] # width of the device in inches
189                 strWi <- strwidth(x$tip.label, "inches") # id. for the tip labels
190                 ## 1.04 comes from that we are using a regular axis system
191                 ## with 4% on both sides of the range of x:
192                 xx.tips <- xx[1:Ntip] * 1.04
193                 ## 'alp' is the conversion coefficient from
194                 ## user coordinates to inches:
195                 alp <- try(uniroot(function(a) max(a*xx.tips + strWi) - pin1,
196                                    c(0, 1e6))$root, silent = TRUE)
197                 ## if the above fails, give 1/3 of the device for the tip labels:
198                 if (is.character(alp)) tmp <- max(xx.tips)*1.5 else {
199                     tmp <- if (show.tip.label) max(xx.tips + strWi/alp) else max(xx.tips)
200                 }
201                 x.lim[2] <- tmp
202             } else x.lim <- c(1, Ntip)
203         } else switch(type, "fan" = {
204             if (show.tip.label) {
205                 offset <- max(nchar(x$tip.label) * 0.018 * max(yy) * cex)
206                 x.lim <- c(min(xx) - offset, max(xx) + offset)
207             } else x.lim <- c(min(xx), max(xx))
208         }, "unrooted" = {
209             if (show.tip.label) {
210                 offset <- max(nchar(x$tip.label) * 0.018 * max(yy) * cex)
211                 x.lim <- c(0 - offset, max(xx) + offset)
212             } else x.lim <- c(0, max(xx))
213         }, "radial" = {
214             if (show.tip.label) {
215                 offset <- max(nchar(x$tip.label) * 0.03 * cex)
216                 x.lim <- c(-1 - offset, 1 + offset)
217             } else x.lim <- c(-1, 1)
218         })
219     } else if (length(x.lim) == 1) {
220         x.lim <- c(0, x.lim)
221         if (phyloORclado && !horizontal) x.lim[1] <- 1
222         if (type %in% c("fan", "unrooted") && show.tip.label)
223           x.lim[1] <- -max(nchar(x$tip.label) * 0.018 * max(yy) * cex)
224         if (type == "radial")
225           x.lim[1] <-
226             if (show.tip.label) -1 - max(nchar(x$tip.label) * 0.03 * cex)
227             else -1
228     }
229     ## mirror the xx:
230     if (phyloORclado && direction == "leftwards") xx <- x.lim[2] - xx
231     if (is.null(y.lim)) {
232         if (phyloORclado) {
233             if (horizontal) y.lim <- c(1, Ntip) else {
234                 y.lim <- c(0, NA)
235                 pin2 <- par("pin")[2] # height of the device in inches
236                 strWi <- strwidth(x$tip.label, "inches")
237                 ## 1.04 comes from that we are using a regular axis system
238                 ## with 4% on both sides of the range of x:
239                 yy.tips <- yy[1:Ntip] * 1.04
240                 ## 'alp' is the conversion coefficient from
241                 ## user coordinates to inches:
242                 alp <- try(uniroot(function(a) max(a*yy.tips + strWi) - pin2,
243                                    c(0, 1e6))$root, silent = TRUE)
244                 ## if the above fails, give 1/3 of the device for the tip labels:
245                 if (is.character(alp)) tmp <- max(yy.tips)*1.5 else {
246                     tmp <- if (show.tip.label) max(yy.tips + strWi/alp) else max(yy.tips)
247                 }
248                 y.lim[2] <- tmp
249             }
250         } else switch(type, "fan" = {
251             if (show.tip.label) {
252                 offset <- max(nchar(x$tip.label) * 0.018 * max(yy) * cex)
253                 y.lim <- c(min(yy) - offset, max(yy) + offset)
254             } else y.lim <- c(min(yy), max(yy))
255         }, "unrooted" = {
256             if (show.tip.label) {
257                 offset <- max(nchar(x$tip.label) * 0.018 * max(yy) * cex)
258                 y.lim <- c(0 - offset, max(yy) + offset)
259             } else y.lim <- c(0, max(yy))
260         }, "radial" = {
261             if (show.tip.label) {
262                 offset <- max(nchar(x$tip.label) * 0.03 * cex)
263                 y.lim <- c(-1 - offset, 1 + offset)
264             } else y.lim <- c(-1, 1)
265         })
266     } else if (length(y.lim) == 1) {
267         y.lim <- c(0, y.lim)
268         if (phyloORclado && horizontal) y.lim[1] <- 1
269         if (type %in% c("fan", "unrooted") && show.tip.label)
270           y.lim[1] <- -max(nchar(x$tip.label) * 0.018 * max(yy) * cex)
271         if (type == "radial")
272           y.lim[1] <- if (show.tip.label) -1 - max(nchar(x$tip.label) * 0.018 * max(yy) * cex) else -1
273     }
274     ## mirror the yy:
275     if (phyloORclado && direction == "downwards") yy <- y.lim[2] - yy
276     if (phyloORclado && root.edge) {
277         if (direction == "leftwards") x.lim[2] <- x.lim[2] + x$root.edge
278         if (direction == "downwards") y.lim[2] <- y.lim[2] + x$root.edge
279     }
280     asp <- if (type %in% c("fan", "radial", "unrooted")) 1 else NA # fixes by Klaus Schliep (2008-03-28 and 2010-08-12)
281     plot(0, type = "n", xlim = x.lim, ylim = y.lim, ann = FALSE, axes = FALSE, asp = asp, ...)
282
283 if (draw) {
284     if (is.null(adj))
285         adj <- if (phyloORclado && direction == "leftwards") 1 else 0
286     if (phyloORclado && show.tip.label) {
287         MAXSTRING <- max(strwidth(x$tip.label, cex = cex))
288         loy <- 0
289         if (direction == "rightwards") {
290             lox <- label.offset + MAXSTRING * 1.05 * adj
291         }
292         if (direction == "leftwards") {
293             lox <- -label.offset - MAXSTRING * 1.05 * (1 - adj)
294             ##xx <- xx + MAXSTRING
295         }
296         if (!horizontal) {
297             psr <- par("usr")
298             MAXSTRING <- MAXSTRING * 1.09 * (psr[4] - psr[3])/(psr[2] - psr[1])
299             loy <- label.offset + MAXSTRING * 1.05 * adj
300             lox <- 0
301             srt <- 90 + srt
302             if (direction == "downwards") {
303                 loy <- -loy
304                 ##yy <- yy + MAXSTRING
305                 srt <- 180 + srt
306             }
307         }
308     }
309     if (type == "phylogram") {
310         phylogram.plot(x$edge, Ntip, Nnode, xx, yy,
311                        horizontal, edge.color, edge.width, edge.lty)
312     } else {
313         if (type == "fan") {
314             ereorder <- match(z$edge[, 2], x$edge[, 2])
315             if (length(edge.color) > 1) {
316                 edge.color <- rep(edge.color, length.out = Nedge)
317                 edge.color <- edge.color[ereorder]
318             }
319             if (length(edge.width) > 1) {
320                 edge.width <- rep(edge.width, length.out = Nedge)
321                 edge.width <- edge.width[ereorder]
322             }
323             if (length(edge.lty) > 1) {
324                 edge.lty <- rep(edge.lty, length.out = Nedge)
325                 edge.lty <- edge.lty[ereorder]
326             }
327             circular.plot(z$edge, Ntip, Nnode, xx, yy, theta,
328                           r, edge.color, edge.width, edge.lty)
329         } else
330         cladogram.plot(x$edge, xx, yy, edge.color, edge.width, edge.lty)
331     }
332     if (root.edge)
333       switch(direction,
334              "rightwards" = segments(0, yy[ROOT], x$root.edge, yy[ROOT]),
335              "leftwards" = segments(xx[ROOT], yy[ROOT], xx[ROOT] + x$root.edge, yy[ROOT]),
336              "upwards" = segments(xx[ROOT], 0, xx[ROOT], x$root.edge),
337              "downwards" = segments(xx[ROOT], yy[ROOT], xx[ROOT], yy[ROOT] + x$root.edge))
338     if (show.tip.label) {
339         if (is.expression(x$tip.label)) underscore <- TRUE
340         if (!underscore) x$tip.label <- gsub("_", " ", x$tip.label)
341
342         if (phyloORclado)
343             text(xx[1:Ntip] + lox, yy[1:Ntip] + loy, x$tip.label, adj = adj,
344                  font = font, srt = srt, cex = cex, col = tip.color)
345
346         if (type == "unrooted") {
347             if (lab4ut == "horizontal") {
348                 y.adj <- x.adj <- numeric(Ntip)
349                 sel <- abs(XY$axe) > 0.75 * pi
350                 x.adj[sel] <- -strwidth(x$tip.label)[sel] * 1.05
351                 sel <- abs(XY$axe) > pi/4 & abs(XY$axe) < 0.75 * pi
352                 x.adj[sel] <- -strwidth(x$tip.label)[sel] * (2 * abs(XY$axe)[sel] / pi - 0.5)
353                 sel <- XY$axe > pi / 4 & XY$axe < 0.75 * pi
354                 y.adj[sel] <- strheight(x$tip.label)[sel] / 2
355                 sel <- XY$axe < -pi / 4 & XY$axe > -0.75 * pi
356                 y.adj[sel] <- -strheight(x$tip.label)[sel] * 0.75
357                 text(xx[1:Ntip] + x.adj * cex, yy[1:Ntip] + y.adj * cex,
358                      x$tip.label, adj = c(adj, 0), font = font,
359                      srt = srt, cex = cex, col = tip.color)
360             } else { # if lab4ut == "axial"
361                 adj <- abs(XY$axe) > pi/2
362                 srt <- 180 * XY$axe / pi
363                 srt[adj] <- srt[adj] - 180
364                 adj <- as.numeric(adj)
365                 xx.tips <- xx[1:Ntip]
366                 yy.tips <- yy[1:Ntip]
367                 if (label.offset) {
368                     xx.tips <- xx.tips + label.offset * cos(XY$axe)
369                     yy.tips <- yy.tips + label.offset * sin(XY$axe)
370                 }
371                 ## `srt' takes only a single value, so can't vectorize this:
372                 ## (and need to 'elongate' these vectors:)
373                 font <- rep(font, length.out = Ntip)
374                 tip.color <- rep(tip.color, length.out = Ntip)
375                 cex <- rep(cex, length.out = Ntip)
376                 for (i in 1:Ntip)
377                     text(xx.tips[i], yy.tips[i], cex = cex[i],
378                          x$tip.label[i], adj = adj[i], font = font[i],
379                          srt = srt[i], col = tip.color[i])
380             }
381         }
382         if (type %in% c("fan", "radial")) {
383             xx.tips <- xx[1:Ntip]
384             yy.tips <- yy[1:Ntip]
385             ## using atan2 considerably facilitates things compared to acos...
386             angle <- atan2(yy.tips, xx.tips) # in radians
387             if (label.offset) {
388                 xx.tips <- xx.tips + label.offset * cos(angle)
389                 yy.tips <- yy.tips + label.offset * sin(angle)
390             }
391             s <- xx.tips < 0
392             angle <- angle * 180/pi # switch to degrees
393             angle[s] <- angle[s] + 180
394             adj <- as.numeric(s)
395             ## `srt' takes only a single value, so can't vectorize this:
396             ## (and need to 'elongate' these vectors:)
397             font <- rep(font, length.out = Ntip)
398             tip.color <- rep(tip.color, length.out = Ntip)
399             cex <- rep(cex, length.out = Ntip)
400             for (i in 1:Ntip)
401                 text(xx.tips[i], yy.tips[i], x$tip.label[i], font = font[i],
402                      cex = cex[i], srt = angle[i], adj = adj[i],
403                      col = tip.color[i])
404         }
405     }
406     if (show.node.label)
407         text(xx[ROOT:length(xx)] + label.offset, yy[ROOT:length(yy)],
408              x$node.label, adj = adj, font = font, srt = srt, cex = cex)
409 }
410     L <- list(type = type, use.edge.length = use.edge.length,
411               node.pos = node.pos, show.tip.label = show.tip.label,
412               show.node.label = show.node.label, font = font,
413               cex = cex, adj = adj, srt = srt, no.margin = no.margin,
414               label.offset = label.offset, x.lim = x.lim, y.lim = y.lim,
415               direction = direction, tip.color = tip.color,
416               Ntip = Ntip, Nnode = Nnode)
417     assign("last_plot.phylo", c(L, list(edge = xe, xx = xx, yy = yy)),
418            envir = .PlotPhyloEnv)
419     invisible(L)
420 }
421
422 phylogram.plot <- function(edge, Ntip, Nnode, xx, yy, horizontal,
423                            edge.color, edge.width, edge.lty)
424 {
425     nodes <- (Ntip + 1):(Ntip + Nnode)
426     if (!horizontal) {
427         tmp <- yy
428         yy <- xx
429         xx <- tmp
430     }
431     ## un trait vertical Ã  chaque noeud...
432     x0v <- xx[nodes]
433     y0v <- y1v <- numeric(Nnode)
434     ## store the index of each node in the 1st column of edge:
435     NodeInEdge1 <- vector("list", Nnode)
436     for (i in nodes) {
437         ii <- i - Ntip
438         j <- NodeInEdge1[[ii]] <- which(edge[, 1] == i)
439         tmp <- range(yy[edge[j, 2]])
440         y0v[ii] <- tmp[1]
441         y1v[ii] <- tmp[2]
442     }
443     ## ... et un trait horizontal partant de chaque tip et chaque noeud
444     ##  vers la racine
445     x0h <- xx[edge[, 1]]
446     x1h <- xx[edge[, 2]]
447     y0h <- yy[edge[, 2]]
448
449     nc <- length(edge.color)
450     nw <- length(edge.width)
451     nl <- length(edge.lty)
452
453     if (nc + nw + nl == 3) {
454         color.v <- edge.color
455         width.v <- edge.width
456         lty.v <- edge.lty
457     } else {
458         Nedge <- dim(edge)[1]
459         edge.color <- rep(edge.color, length.out = Nedge)
460         edge.width <- rep(edge.width, length.out = Nedge)
461         edge.lty <- rep(edge.lty, length.out = Nedge)
462         DF <- data.frame(edge.color, edge.width, edge.lty, stringsAsFactors = FALSE)
463         color.v <- rep("black", Nnode)
464         width.v <- rep(1, Nnode)
465         lty.v <- rep(1, Nnode)
466         for (i in 1:Nnode) {
467             br <- NodeInEdge1[[i]]
468             if (length(br) > 2) {
469                 x <- unique(DF[br, 1])
470                 if (length(x) == 1) color.v[i] <- x
471                 x <- unique(DF[br, 2])
472                 if (length(x) == 1) width.v[i] <- x
473                 x <- unique(DF[br, 3])
474                 if (length(x) == 1) lty.v[i] <- x
475             } else {
476                 A <- br[1]
477                 B <- br[2]
478                 if (any(DF[A, ] != DF[B, ])) {
479                     color.v[i] <- edge.color[B]
480                     width.v[i] <- edge.width[B]
481                     lty.v[i] <- edge.lty[B]
482                     ## add a new line:
483                     y0v <- c(y0v, y0v[i])
484                     y1v <- c(y1v, yy[i + Ntip])
485                     x0v <- c(x0v, x0v[i])
486                     color.v <- c(color.v, edge.color[A])
487                     width.v <- c(width.v, edge.width[A])
488                     lty.v <- c(lty.v, edge.lty[A])
489                     ## shorten the line:
490                     y0v[i] <- yy[i + Ntip]
491                 } else {
492                     color.v[i] <- edge.color[A]
493                     width.v[i] <- edge.width[A]
494                     lty.v[i] <- edge.lty[A]
495                 }
496             }
497         }
498     }
499
500     if (horizontal) {
501         segments(x0h, y0h, x1h, y0h, col = edge.color, lwd = edge.width, lty = edge.lty) # draws horizontal lines
502         segments(x0v, y0v, x0v, y1v, col = color.v, lwd = width.v, lty = lty.v) # draws vertical lines
503     } else {
504         segments(y0h, x0h, y0h, x1h, col = edge.color, lwd = edge.width, lty = edge.lty) # draws vertical lines
505         segments(y0v, x0v, y1v, x0v, col = color.v, lwd = width.v, lty = lty.v) # draws horizontal lines
506     }
507 }
508
509 cladogram.plot <- function(edge, xx, yy, edge.color, edge.width, edge.lty)
510     segments(xx[edge[, 1]], yy[edge[, 1]], xx[edge[, 2]], yy[edge[, 2]],
511              col = edge.color, lwd = edge.width, lty = edge.lty)
512
513 circular.plot <- function(edge, Ntip, Nnode, xx, yy, theta,
514                           r, edge.color, edge.width, edge.lty)
515 ### 'edge' must be in pruningwise order
516 {
517     r0 <- r[edge[, 1]]
518     r1 <- r[edge[, 2]]
519     theta0 <- theta[edge[, 2]]
520     costheta0 <- cos(theta0)
521     sintheta0 <- sin(theta0)
522
523     x0 <- r0 * costheta0
524     y0 <- r0 * sintheta0
525     x1 <- r1 * costheta0
526     y1 <- r1 * sintheta0
527
528     segments(x0, y0, x1, y1, col = edge.color, lwd = edge.width, lty = edge.lty)
529
530     tmp <- which(diff(edge[, 1]) != 0)
531     start <- c(1, tmp + 1)
532     Nedge <- dim(edge)[1]
533     end <- c(tmp, Nedge)
534
535     ## function dispatching the features to the arcs
536     foo <- function(edge.feat, default) {
537         if (length(edge.feat) == 1) return(rep(edge.feat, Nnode))
538         else {
539             edge.feat <- rep(edge.feat, length.out = Nedge)
540             feat.arc <- rep(default, Nnode)
541             for (k in 1:Nnode) {
542                 tmp <- edge.feat[start[k]]
543                 if (tmp == edge.feat[end[k]]) feat.arc[k] <- tmp
544             }
545         }
546         feat.arc
547     }
548     co <- foo(edge.color, "black")
549     lw <- foo(edge.width, 1)
550     ly <- foo(edge.lty, 1)
551
552     for (k in 1:Nnode) {
553         i <- start[k]
554         j <- end[k]
555         X <- rep(r[edge[i, 1]], 100)
556         Y <- seq(theta[edge[i, 2]], theta[edge[j, 2]], length.out = 100)
557         lines(X*cos(Y), X*sin(Y), col = co[k], lwd = lw[k], lty = ly[k])
558     }
559 }
560
561 unrooted.xy <- function(Ntip, Nnode, edge, edge.length, nb.sp)
562 {
563     foo <- function(node, ANGLE, AXIS) {
564         ind <- which(edge[, 1] == node)
565         sons <- edge[ind, 2]
566         start <- AXIS - ANGLE/2
567         for (i in 1:length(sons)) {
568             h <- edge.length[ind[i]]
569             angle[sons[i]] <<- alpha <- ANGLE*nb.sp[sons[i]]/nb.sp[node]
570             axis[sons[i]] <<- beta <- start + alpha/2
571             start <- start + alpha
572             xx[sons[i]] <<- h*cos(beta) + xx[node]
573             yy[sons[i]] <<- h*sin(beta) + yy[node]
574         }
575         for (i in sons)
576           if (i > Ntip) foo(i, angle[i], axis[i])
577     }
578     Nedge <- dim(edge)[1]
579     yy <- xx <- numeric(Ntip + Nnode)
580     ## `angle': the angle allocated to each node wrt their nb of tips
581     ## `axis': the axis of each branch
582     axis <- angle <- numeric(Ntip + Nnode)
583     ## start with the root...
584     foo(Ntip + 1L, 2*pi, 0)
585
586     M <- cbind(xx, yy)
587     axe <- axis[1:Ntip] # the axis of the terminal branches (for export)
588     axeGTpi <- axe > pi
589     ## insures that returned angles are in [-PI, +PI]:
590     axe[axeGTpi] <- axe[axeGTpi] - 2*pi
591     list(M = M, axe = axe)
592 }
593
594 node.depth <- function(phy)
595 {
596     n <- length(phy$tip.label)
597     m <- phy$Nnode
598     N <- dim(phy$edge)[1]
599     phy <- reorder(phy, order = "pruningwise")
600     .C("node_depth", as.integer(n), as.integer(m),
601        as.integer(phy$edge[, 1]), as.integer(phy$edge[, 2]),
602        as.integer(N), double(n + m), DUP = FALSE, PACKAGE = "ape")[[6]]
603 }
604
605 plot.multiPhylo <- function(x, layout = 1, ...)
606 {
607     if (layout > 1)
608       layout(matrix(1:layout, ceiling(sqrt(layout)), byrow = TRUE))
609     else layout(matrix(1))
610     if (!par("ask")) {
611         par(ask = TRUE)
612         on.exit(par(ask = FALSE))
613     }
614     for (i in 1:length(x)) plot(x[[i]], ...)
615 }
616
617 trex <- function(phy, title = TRUE, subbg = "lightyellow3",
618                  return.tree = FALSE, ...)
619 {
620     lastPP <- get("last_plot.phylo", envir = .PlotPhyloEnv)
621     devmain <- dev.cur() # where the main tree is plotted
622
623     restore <- function() {
624         dev.set(devmain)
625         assign("last_plot.phylo", lastPP, envir = .PlotPhyloEnv)
626     }
627
628     on.exit(restore())
629     NEW <- TRUE
630     cat("Click close to a node. Right-click to exit.\n")
631     repeat {
632         x <- identify.phylo(phy, quiet = TRUE)
633         if (is.null(x)) return(invisible(NULL)) else {
634             x <- x$nodes
635             if (is.null(x)) cat("Try again!\n") else {
636                 if (NEW) {
637                     dev.new()
638                     par(bg = subbg)
639                     devsub <- dev.cur()
640                     NEW <- FALSE
641                 } else dev.set(devsub)
642
643                 tr <- extract.clade(phy, x)
644                 plot(tr, ...)
645                 if (is.character(title)) title(title)
646                 else if (title) {
647                      tl <-
648                          if (is.null(phy$node.label))
649                          paste("From node #", x, sep = "")
650                          else paste("From", phy$node.label[x - Ntip(phy)])
651                      title(tl)
652                 }
653                 if (return.tree) return(tr)
654                 restore()
655             }
656         }
657     }
658 }
659
660 kronoviz <- function(x, layout = length(x), horiz = TRUE, ...)
661 {
662     par(mar = rep(0.5, 4), oma = rep(2, 4))
663     rts <- sapply(x, function(x) branching.times(x)[1])
664     maxrts <- max(rts)
665     lim <- cbind(rts - maxrts, rts)
666     Ntree <- length(x)
667     Ntips <- sapply(x, Ntip)
668     if (horiz) {
669         nrow <- layout
670         w <- 1
671         h <- Ntips
672     } else {
673         nrow <- 1
674         w <- Ntips
675         h <- 1
676     }
677     layout(matrix(1:layout, nrow), widths = w, heights = h)
678     if (layout > Ntree && !par("ask")) {
679         par(ask = TRUE)
680         on.exit(par(ask = FALSE))
681     }
682     if (horiz) {
683         for (i in 1:Ntree)
684             plot(x[[i]], x.lim = lim[i, ], ...)
685     } else {
686         for (i in 1:Ntree)
687             plot(x[[i]], y.lim = lim[i, ], direction = "u", ...)
688     }
689     axisPhylo(if (horiz) 1 else 4) # better if the deepest tree is last ;)
690 }