Debian Codegraph @

R/tanglegram.R

raw
1 # Copyright (C) Tal Galili
2 #
3 # This file is part of dendextend.
4 #
5 # dendextend is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # dendextend is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # A copy of the GNU General Public License is available at
16 # http://www.r-project.org/Licenses/
17 #
18
19
20
21
22
23
24
25
26
27
28 ### An internal function for plot_horiz.dendrogram
29 ### This is basically "plotNode", but with options to make it work
30 ### with horizontal trees.
31 plotNode_horiz <- function(x1, x2, subtree, type, center, leaflab, dLeaf, nodePar,
32 edgePar, horiz = FALSE,
33 text_pos = 2, text_offset = 0) {
34 .midDend <- stats_.midDend
35 plotNodeLimit <- stats_plotNodeLimit
36 plotNode <- stats_plotNode
37
38 inner <- !is.leaf(subtree) && x1 != x2
39 yTop <- attr(subtree, "height")
40 bx <- plotNodeLimit(x1, x2, subtree, center)
41 xTop <- bx$x
42 hasP <- !is.null(nPar <- attr(subtree, "nodePar"))
43 if (!hasP) {
44 nPar <- nodePar
45 }
46 if (getOption("verbose")) {
47 cat(if (inner) {
48 "inner node"
49 } else {
50 "leaf"
51 }, ":")
52 if (!is.null(nPar)) {
53 cat(" with node pars\n")
54 str(nPar)
55 }
56 cat(if (inner) {
57 paste(" height", formatC(yTop), "; ")
58 }, "(x1,x2)= (",
59 formatC(x1, width = 4), ",", formatC(x2, width = 4),
60 ")", "--> xTop=", formatC(xTop, width = 8), "\n",
61 sep = ""
62 )
63 }
64 Xtract <- function(nam, L, default, indx) rep(if (nam %in%
65 names(L)) {
66 L[[nam]]
67 } else {
68 default
69 }, length.out = indx)[indx]
70 asTxt <- function(x) if (is.character(x) || is.expression(x) ||
71 is.null(x)) {
72 x
73 } else {
74 as.character(x)
75 }
76 i <- if (inner || hasP) {
77 1
78 } else {
79 2
80 }
81 if (!is.null(nPar)) {
82 pch <- Xtract("pch", nPar, default = 1L:2, i)
83 cex <- Xtract("cex", nPar, default = c(1, 1), i)
84 col <- Xtract("col", nPar, default = par("col"), i)
85 bg <- Xtract("bg", nPar, default = par("bg"), i)
86 points(if (horiz) {
87 cbind(yTop, xTop)
88 } else {
89 cbind(xTop, yTop)
90 },
91 pch = pch, bg = bg, col = col,
92 cex = cex
93 )
94 }
95 if (leaflab == "textlike") {
96 p.col <- Xtract("p.col", nPar, default = "white", i)
97 }
98 lab.col <- Xtract("lab.col", nPar,
99 default = par("col"),
100 i
101 )
102 lab.cex <- Xtract("lab.cex", nPar, default = c(1, 1), i)
103 lab.font <- Xtract("lab.font", nPar,
104 default = par("font"),
105 i
106 )
107 lab.xpd <- Xtract("xpd", nPar, default = c(TRUE, TRUE), i)
108 if (is.leaf(subtree)) {
109 if (leaflab == "perpendicular") {
110 if (horiz) {
111 if (text_pos == 2) {
112 X <- yTop - dLeaf * lab.cex ##############
113 } else {
114 X <- yTop + dLeaf * lab.cex ##############
115 }
116 Y <- xTop
117 srt <- 0
118 adj <- c(0, 0.5)
119 }
120 else {
121 Y <- yTop - dLeaf * lab.cex
122 X <- xTop
123 srt <- 90
124 adj <- 1
125 }
126 nodeText <- asTxt(attr(subtree, "label"))
127 text(X, Y, nodeText,
128 xpd = lab.xpd, srt = srt, adj = adj,
129 cex = lab.cex, col = lab.col, font = lab.font,
130 pos = text_pos, offset = text_offset
131 ) ###########
132 }
133 }
134 else if (inner) {
135 segmentsHV <- function(x0, y0, x1, y1) {
136 if (horiz) {
137 segments(y0, x0, y1, x1,
138 col = col, lty = lty,
139 lwd = lwd
140 )
141 } else {
142 segments(x0, y0, x1, y1,
143 col = col, lty = lty,
144 lwd = lwd
145 )
146 }
147 }
148 for (k in seq_along(subtree)) {
149 child <- subtree[[k]]
150 yBot <- attr(child, "height")
151 if (getOption("verbose")) {
152 cat("ch.", k, "@ h=", yBot, "; ")
153 }
154 if (is.null(yBot)) {
155 yBot <- 0
156 }
157 xBot <- if (center) {
158 mean(bx$limit[k:(k + 1)])
159 } else {
160 bx$limit[k] + .midDend(child)
161 }
162 hasE <- !is.null(ePar <- attr(child, "edgePar"))
163 if (!hasE) {
164 ePar <- edgePar
165 }
166 i <- if (!is.leaf(child) || hasE) {
167 1
168 } else {
169 2
170 }
171 col <- Xtract("col", ePar,
172 default = par("col"),
173 i
174 )
175 lty <- Xtract("lty", ePar,
176 default = par("lty"),
177 i
178 )
179 lwd <- Xtract("lwd", ePar,
180 default = par("lwd"),
181 i
182 )
183 if (type == "triangle") {
184 segmentsHV(xTop, yTop, xBot, yBot)
185 }
186 else {
187 segmentsHV(xTop, yTop, xBot, yTop)
188 segmentsHV(xBot, yTop, xBot, yBot)
189 }
190 vln <- NULL
191 if (is.leaf(child) && leaflab == "textlike") {
192 nodeText <- asTxt(attr(child, "label"))
193 if (getOption("verbose")) {
194 cat("-- with \"label\"", format(nodeText))
195 }
196 hln <- 0.6 * strwidth(nodeText, cex = lab.cex) / 2
197 vln <- 1.5 * strheight(nodeText, cex = lab.cex) / 2
198 rect(xBot - hln, yBot, xBot + hln, yBot + 2 *
199 vln, col = p.col)
200 text(xBot, yBot + vln, nodeText,
201 xpd = lab.xpd,
202 cex = lab.cex, col = lab.col, font = lab.font
203 ) # , pos = text_pos)
204 }
205 if (!is.null(attr(child, "edgetext"))) {
206 edgeText <- asTxt(attr(child, "edgetext"))
207 if (getOption("verbose")) {
208 cat("-- with \"edgetext\"", format(edgeText))
209 }
210 if (!is.null(vln)) {
211 mx <- if (type == "triangle") {
212 (xTop + xBot + ((xTop - xBot) / (yTop - yBot)) *
213 vln) / 2
214 } else {
215 xBot
216 }
217 my <- (yTop + yBot + 2 * vln) / 2
218 }
219 else {
220 mx <- if (type == "triangle") {
221 (xTop + xBot) / 2
222 } else {
223 xBot
224 }
225 my <- (yTop + yBot) / 2
226 }
227 p.col <- Xtract("p.col", ePar,
228 default = "white",
229 i
230 )
231 p.border <- Xtract("p.border", ePar,
232 default = par("fg"),
233 i
234 )
235 p.lwd <- Xtract("p.lwd", ePar,
236 default = lwd,
237 i
238 )
239 p.lty <- Xtract("p.lty", ePar,
240 default = lty,
241 i
242 )
243 t.col <- Xtract("t.col", ePar,
244 default = col,
245 i
246 )
247 t.cex <- Xtract("t.cex", ePar, default = 1, i)
248 t.font <- Xtract("t.font", ePar,
249 default = par("font"),
250 i
251 )
252 vlm <- strheight(c(edgeText, "h"), cex = t.cex) / 2
253 hlm <- strwidth(c(edgeText, "m"), cex = t.cex) / 2
254 hl3 <- c(hlm[1L], hlm[1L] + hlm[2L], hlm[1L])
255 if (horiz) {
256 polygon(my + c(-hl3, hl3), mx + sum(vlm) *
257 c(-1L:1L, 1L:-1L),
258 col = p.col, border = p.border,
259 lty = p.lty, lwd = p.lwd
260 )
261 text(my, mx, edgeText,
262 cex = t.cex, col = t.col,
263 font = t.font
264 ) # , pos = text_pos)
265 }
266 else {
267 polygon(mx + c(-hl3, hl3), my + sum(vlm) *
268 c(-1L:1L, 1L:-1L),
269 col = p.col, border = p.border,
270 lty = p.lty, lwd = p.lwd
271 )
272 text(mx, my, edgeText,
273 cex = t.cex, col = t.col,
274 font = t.font
275 )
276 }
277 }
278 # plotNode_horiz
279 Recall(bx$limit[k], bx$limit[k + 1],
280 subtree = child, #########
281 type, center, leaflab, dLeaf, nodePar, edgePar,
282 horiz, text_pos = text_pos, text_offset = text_offset
283 ) ########
284 }
285 }
286 invisible()
287 }
288
289
290
291
292
293
294
295 #' @title Plotting a left-tip-adjusted horizontal dendrogram
296 #' @export
297 #' @description
298 #' The default \code{plot(dend, horiz = TRUE)}, gives us a dendrogram tree plot
299 #' with the tips turned right. The current function enables the creation of
300 #' the same tree, but with the tips turned left. The main challange in doing this
301 #' is finding the distance of the labels from the leaves tips - which is solved
302 #' with this function.
303 #' @param x tree object (dendrogram)
304 #' @param type a character vector with either "rectangle" or "triangle" (passed to \link{plot.dendrogram})
305 #' @param center logical; if TRUE, nodes are plotted centered with respect to
306 #' the leaves in the branch. Otherwise (default), plot them in the
307 #' middle of all direct child nodes.
308 #' @param edge.root logical; if true, draw an edge to the root node.
309 #' @param dLeaf a number specifying the distance in user coordinates between
310 #' the tip of a leaf and its label. If NULL as per default, 3/4 of a letter
311 #' width is used.
312 #' @param horiz logical indicating if the dendrogram should be
313 #' drawn horizontally or not. In this function it MUST be TRUE!
314 #' @param xaxt graphical parameters, or arguments for other methods.
315 #' @param yaxt graphical parameters, or arguments for other methods.
316 #' @param xlim (NULL) optional x- and y-limits of the plot, passed to plot.default.
317 #' The defaults for these show the full dendrogram.
318 #' @param ylim (NULL) optional x- and y-limits of the plot, passed to plot.default.
319 #' The defaults for these show the full dendrogram.
320 #' @param nodePar NULL.
321 #' @param edgePar list()
322 #' @param leaflab c("perpendicular", "textlike", "none")
323 #' @param side logical (TRUE). Should the tips of the drawn tree be facing
324 #' the left side. This is the important feature of this function.
325 #' @param text_pos integer from either 1 to 4 (2). Two relevant values
326 #' are 2 and 4. 2 (default) means that the labels are alligned to the
327 #' tips of the tree leaves. 4 will have the labels allign to the left,
328 #' making them look like they were when the tree was on the left side
329 #' (with leaves tips facing to the right).
330 #' @param ... passed to \link{plot}.
331 #' @return The invisiable dLeaf value.
332 #' @source
333 #' This function is based on replicating \link{plot.dendrogram}.
334 #' In fact, I'd be happy if in the future, some tweaks could be make to
335 #' \link{plot.dendrogram}, so that it would replace the need for this function.
336 #'
337 #' @seealso \link{plot.dendrogram}, \link{tanglegram}
338 #' @examples
339 #' \dontrun{
340 #' dend <- USArrests[1:10, ] %>%
341 #' dist() %>%
342 #' hclust() %>%
343 #' as.dendrogram()
344 #'
345 #' par(mfrow = c(1, 2), mar = rep(6, 4))
346 #' plot_horiz.dendrogram(dend, side = FALSE)
347 #' plot_horiz.dendrogram(dend, side = TRUE)
348 #' # plot_horiz.dendrogram(dend, side=TRUE, dLeaf= 0)
349 #' # plot_horiz.dendrogram(dend, side=TRUE, nodePar = list(pos = 1))
350 #' # sadly, lab.pos is not implemented yet,
351 #' ## so the labels can not be right aligned...
352 #'
353 #'
354 #' plot_horiz.dendrogram(dend, side = F)
355 #' plot_horiz.dendrogram(dend, side = TRUE, dLeaf = 0, xlim = c(100, -10)) # bad
356 #' plot_horiz.dendrogram(dend, side = TRUE, text_offset = 0)
357 #' plot_horiz.dendrogram(dend, side = TRUE, text_offset = 0, text_pos = 4)
358 #' }
359 plot_horiz.dendrogram <- function(x,
360 type = c("rectangle", "triangle"),
361 center = FALSE,
362 edge.root = is.leaf(x) || !is.null(attr(x, "edgetext")),
363 dLeaf = NULL,
364 horiz = TRUE,
365 xaxt = "n", yaxt = "s",
366 xlim = NULL, ylim = NULL,
367 nodePar = NULL, edgePar = list(),
368 leaflab = c(
369 "perpendicular",
370 "textlike", "none"
371 ),
372 side = TRUE,
373 text_pos = 2,
374 ...) {
375 # reproduces plot.dendrogram in order to set the correct
376 # strwidth for the labels when using revers horiz!
377 # @param side logical (FALSE). To which direction should the dendrogram turn.
378 # if FALSE (default) then we will get the standard left side dendrogram.
379 # if TRUE, then we will have a right turning dendrogram.
380
381 if (!is.dendrogram(x)) x <- as.dendrogram(x)
382 if (!horiz) stop("This function was created ONLY for horiz==TRUE.")
383
384 # if NOT side - then plot as usual
385 if (!side) {
386 plot(x,
387 center = center,
388 type = type, nodePar = nodePar, edgePar = edgePar, leaflab = leaflab,
389 edge.root = edge.root,
390 dLeaf = dLeaf,
391 horiz = horiz,
392 xaxt = xaxt, yaxt = yaxt,
393 xlim = xlim, ylim = ylim, ...
394 )
395 return(invisible(NULL))
396 }
397
398 #######################
399 ### The same as:
400 #### plot.dendrogram
401 type <- match.arg(type)
402 leaflab <- match.arg(leaflab)
403 hgt <- attr(x, "height")
404 if (edge.root && is.logical(edge.root)) {
405 edge.root <- 0.0625 * if (is.leaf(x)) {
406 1
407 } else {
408 hgt
409 }
410 }
411 mem.x <- stats_.memberDend(x)
412 yTop <- hgt + edge.root
413 if (center) {
414 x1 <- 0.5
415 x2 <- mem.x + 0.5
416 }
417 else {
418 x1 <- 1
419 x2 <- mem.x
420 }
421 xl. <- c(x1 - 1 / 2, x2 + 1 / 2)
422 yl. <- c(0, yTop)
423 if (horiz) {
424 tmp <- xl.
425 xl. <- rev(yl.)
426 yl. <- tmp
427 tmp <- xaxt
428 xaxt <- yaxt
429 yaxt <- tmp
430 }
431 if (missing(xlim) || is.null(xlim)) {
432 xlim <- xl.
433 }
434 if (missing(ylim) || is.null(ylim)) {
435 ylim <- yl.
436 }
437 dev.hold()
438 on.exit(dev.flush())
439
440 #######################
441 ### NEW code
442
443 # for right_side
444 # if(side) {
445
446 xlim <- rev(xlim)
447
448 plot(0,
449 xlim = xlim, ylim = ylim, type = "n", xlab = "",
450 ylab = "", xaxt = xaxt, yaxt = yaxt, frame.plot = FALSE, ...
451 ) # , axes = FALSE)
452
453
454 labels_x <- labels(x)
455 max_labels_x <- labels_x[which.max(nchar(labels_x))]
456 base_dLeaf <- strwidth(max_labels_x)
457
458 if (is.null(dLeaf)) {
459 if (text_pos == 2) {
460 dLeaf <- 0.75 * strwidth("w")
461 } else {
462 dLeaf <- -0.75 * strwidth("w") - base_dLeaf
463 }
464 ### (if (horiz) else strheight("x")) ## this function gives ONLY horiz= TRUE
465 } else {
466 if (text_pos != 2) dLeaf <- dLeaf - base_dLeaf
467 }
468
469 # par(new=TRUE)
470 # } # else {
471 # # the usual stuff...
472
473 # plot(x,
474 # horiz=horiz,
475 # center = center,
476 # edge.root = edge.root,
477 # dLeaf = dLeaf,
478 # xaxt = yaxt, yaxt = xaxt, # these are reversed in order to be re-reversed later due to the horiz=TRUE in this function...
479 # xlim=xlim, ylim=ylim,
480 # ...)
481 # if(side) par(new=FALSE)
482
483 ###### back to the function as usual:
484 if (edge.root) {
485 x0 <- stats_plotNodeLimit(x1, x2, x, center)$x
486 if (horiz) {
487 segments(hgt, x0, yTop, x0)
488 } else {
489 segments(x0, hgt, x0, yTop)
490 }
491 if (!is.null(et <- attr(x, "edgetext"))) {
492 my <- mean(hgt, yTop)
493 if (horiz) {
494 text(my, x0, et)
495 } else {
496 text(x0, my, et)
497 }
498 }
499 }
500
501 # stats_plotNode
502 # @param text_offset Numeric (NULL). This value gives the offset of the label
503 # from the specified coordinate in fractions of a character width.
504 # If NULL (default) then 3/4 of a letter width is used.
505 #
506 # This number overrides dLeaf.
507
508
509 plotNode_horiz(x1, x2, x,
510 type = type, center = center, leaflab = leaflab,
511 dLeaf = dLeaf, nodePar = nodePar, edgePar = edgePar,
512 horiz = horiz, text_pos = text_pos
513 )
514
515 return(invisible(dLeaf))
516 }
517
518 # # stats_plot.dendrogram
519 # # stats_plotNode
520
521
522
523
524
525
526
527
528
529
530
531
532 #' @title Tanglegram plot
533 #' @export
534 #' @rdname tanglegram
535 #' @description
536 #' Plots a tanglegram plot of a side by side trees.
537 #'
538 #' @author Tal Galili, Johan Renaudie
539 #'
540 #'
541 #' @param dend1 tree object (dendrogram/dendlist/hclust/phylo), plotted on the left
542 #' @param dend2 tree object (dendrogram/hclust/phylo), plotted on the right
543 #' @param which an integer vector of length 2, indicating
544 #' which of the trees in the dendlist object should be plotted
545 #' @param sort logical (FALSE). Should the dendrogram's labels be "sorted"?
546 #' (might give a better tree in some cases).
547 #' @param color_lines a vector of colors for the lines connected the labels.
548 #' If the colors are shorter than the number of labels, they are recycled
549 #' (and a warning is issued).
550 #' The colors in the vector are applied on the lines from the bottom up.
551 #' @param lwd width of the lines connecting the labels. (default is 3.5)
552 #' @param edge.lwd width of the dendrograms lines. Default is NULL.
553 #' If set, then it switches `highlight_branches_lwd` to FALSE. If you want thicker
554 #' lines which reflect the height, please use \link{highlight_branches_lwd} on the
555 #' dendrograms/dendlist.
556 #' @param columns_width a vector with three elements, giving the relative
557 #' sizes of the the three plots (left dendrogram, connecting lines,
558 #' right dendrogram). This is passed to \link{layout} if parameter just_one is TRUE.
559 #' The default is: c(5,3,5)
560 #' @param margin_top the number of lines of margin to be specified on the top
561 #' of the plots.
562 #' @param margin_bottom the number of lines of margin to be specified on the
563 #' bottom of the plots.
564 #' @param margin_inner margin_bottom the number of lines of margin
565 #' to be specified on the inner distence between the dendrograms
566 #' and the connecting lines.
567 #' @param margin_outer margin_bottom the number of lines of margin
568 #' to be specified on the outer distence between the dendrograms
569 #' and the connecting lines.
570 #' @param left_dendo_mar mar parameters of the left dendrgoram.
571 #' @param right_dendo_mar mar parameters of the right dendrgoram.
572 #' @param intersecting logical (TRUE). Should the leaves of the two dendrograms
573 #' be pruned so that the two trees will have the same labels?
574 #' @param dLeaf a number specifying the distance in user coordinates between
575 #' the tip of a leaf and its label. If NULL, as per default,
576 #' 3/4 of a letter width or height is used.
577 #'
578 #' Notice that if we are comparing two dendrograms with different
579 #' heights, manually changing dLeaf will affect both trees differently.
580 #' In such a case, it is recommanded to manually change dLeaf_left
581 #' and dLeaf_right.
582 #' This can be especially important when changing the lab.cex of the
583 #' dendrogram's labels.
584 #' Alternatively, one could manually set the xlim parameter for both
585 #' trees, which will force the proportion of distances of the
586 #' labels from the trees to remain the same.
587 #'
588 #' @param dLeaf_left dLeaf of the left dendrogram, by default it is equal to dLeaf (often negative).
589 #' @param dLeaf_right dLeaf of the right dendrogram, by default it is equal to minus dLeaf (often positive).
590 #' @param axes logical (TRUE). Should plot axes be plotted?
591 #' @param type type of plot ("t"/"r" = triangle or rectangle)
592 #' @param lab.cex numeric scalar, influanicing the cex size of the labels.
593 #' @param remove_nodePar logical (FALSE). Should the nodePar of the leaves be
594 #' removed? (useful when the trees' leaves has too many parameters on them)
595 #' @param main Character. Title above the connecting lines.
596 #' @param main_left Character. Title of the left dendrogram.
597 #' @param main_right Character. Title of the right dendrogram.
598 #' @param sub Character. Title below the connecting lines.
599 #' @param k_labels integer. Number of groups by which to color the leaves.
600 #' @param k_branches integer. Number of groups by which to color the branches.
601 #' @param rank_branches logical (FALSE). Should the branches heights be adjusted?
602 #' (setting this to TRUE - can make it easier for
603 #' comparing topological differences)
604 #' @param hang logical (FALSE). Should we hang the leaves of the trees?
605 #' @param match_order_by_labels logical (TRUE). Should the leaves value order
606 #' be matched between the two trees based on labels? This is a MUST in order
607 #' to have the lines connect the correct labels. Set this to FALSE if you
608 #' want to make the plotting a bit faster, and only after you are sure
609 #' the labels and orders are correctly aligned.
610 #' @param cex_main A numerical value giving the amount by which plotting title
611 #' should be magnified relative to the default.
612 #' @param cex_main_left see cex_main.
613 #' @param cex_main_right see cex_main.
614 #' @param cex_sub see cex_main.
615 #' @param highlight_distinct_edges logical (default is TRUE). If to highlight distinct edges in each tree (by changing their line types to 2).
616 #' (notice that this can be slow on large trees)
617 #'
618 #' This parameter will automatically be turned off if the tree already comes with a "lty" edgePar
619 #' (this is checked using \link{has_edgePar}). A "lty" can be removed by using set("clear_branches"), by
620 #' removing all of the edgePar parameters of the dendrogram.
621 #'
622 #' @param common_subtrees_color_lines logical (default is TRUE). color the connecting line based on the common subtrees of both dends.
623 #' This only works if
624 #' (notice that this can be slow on large trees)
625 #' @param common_subtrees_color_lines_default_single_leaf_color When representing edges between common subtrees
626 #' (i.e. common_subtrees_color_branches = TRUE), this parameter sets the color of edges for subtrees that are NOT common.
627 #' Default is "grey"
628 #' @param common_subtrees_color_branches logical (default is FALSE).
629 #' Color the branches of both dends based on the common subtrees.
630 #' (notice that this can be slow on large trees)
631 #' This is FALSE by default since it will override the colors of the existing tree.
632 #' @param highlight_branches_col logical (default is FALSE). Should \link{highlight_branches_col} be used on the dendrograms.
633 #'
634 #' This parameter will automatically be turned off if the tree already comes with a "col" edgePar
635 #' (this is checked using \link{has_edgePar}). A "lty" can be removed by using set("clear_branches"), by
636 #' removing all of the edgePar parameters of the dendrogram.
637 #'
638 #' @param highlight_branches_lwd logical (default is TRUE). Should \link{highlight_branches_lwd} be used on the dendrograms.
639 #'
640 #' This parameter will automatically be turned off if the tree already comes with a "lwd" edgePar
641 #' (this is checked using \link{has_edgePar}). A "lty" can be removed by using set("clear_branches"), by
642 #' removing all of the edgePar parameters of the dendrogram.
643 #'
644 #' @param faster logical (FALSE). If TRUE, it overrides some other parameters to
645 #' have them turned off so that the plotting will go a tiny bit faster.
646 #' @param just_one logical (TRUE). If FALSE, it means at least two tanglegrams
647 #' will be plotted on the same page and so \link{layout} is not passed.
648 #' See: \url{https://stackoverflow.com/q/39784746/4137985}
649 #' @param ... not used.
650 #' @details
651 #' Notice that tanglegram does not "resize" well. In case you are resizing your
652 #' window you would need to re-run the function.
653 #'
654 #' @return An invisible \link{dendlist}, with two trees after being
655 #' modified during the creation of the tanglegram.
656 #' @source
657 #' The function is based on code from Johan Renaudie (plannapus), after major revisions. See:
658 #' \url{https://stackoverflow.com/questions/12456768/duelling-dendrograms-in-r-placing-dendrograms-back-to-back-in-r}
659 #'
660 #' As far as I could tell, this code was originally inspired by Dylan Beaudette
661 #' function \code{dueling.dendrograms} from the sharpshootR package:
662 #' \url{https://CRAN.R-project.org/package=sharpshootR}
663 #' tanglegram
664 #' @seealso \link{remove_leaves_nodePar}, \link{plot_horiz.dendrogram}, \link{rank_branches},
665 #' \link{hang.dendrogram}
666 #' @examples
667 #' \dontrun{
668 #' set.seed(23235)
669 #' ss <- sample(1:150, 10)
670 #' dend1 <- iris[ss, -5] %>%
671 #' dist() %>%
672 #' hclust("com") %>%
673 #' as.dendrogram()
674 #' dend2 <- iris[ss, -5] %>%
675 #' dist() %>%
676 #' hclust("sin") %>%
677 #' as.dendrogram()
678 #' dend12 <- dendlist(dend1, dend2)
679 #'
680 #' dend12 %>% tanglegram()
681 #'
682 #' tanglegram(dend1, dend2)
683 #' tanglegram(dend1, dend2, sort = TRUE)
684 #' tanglegram(dend1, dend2, remove_nodePar = TRUE)
685 #' tanglegram(dend1, dend2, k_labels = 6, k_branches = 4)
686 #'
687 #' tanglegram(dend1, dend2,
688 #' lab.cex = 2, edge.lwd = 3,
689 #' margin_inner = 5, type = "t", center = TRUE
690 #' )
691 #'
692 #'
693 #' ## works nicely:
694 #' tanglegram(dend1, dend2,
695 #' lab.cex = 2, edge.lwd = 3,
696 #' margin_inner = 3.5, type = "t", center = TRUE,
697 #' dLeaf = -0.1, xlim = c(7, 0),
698 #' k_branches = 3
699 #' )
700 #'
701 #'
702 #' # using rank_branches can make the comparison even easier
703 #' tanglegram(rank_branches(dend1), rank_branches(dend2),
704 #' lab.cex = 2, edge.lwd = 3,
705 #' margin_inner = 3.5, type = "t", center = TRUE,
706 #' dLeaf = -0.1, xlim = c(5.1, 0), columns_width = c(5, 1, 5),
707 #' k_branches = 3
708 #' )
709 #'
710 #'
711 #'
712 #' ########
713 #' ## Nice example of some colored trees
714 #'
715 #' # see the coloring of common sub trees:
716 #' set.seed(23235)
717 #' ss <- sample(1:150, 10)
718 #' dend1 <- iris[ss, -5] %>%
719 #' dist() %>%
720 #' hclust("com") %>%
721 #' as.dendrogram()
722 #' dend2 <- iris[ss, -5] %>%
723 #' dist() %>%
724 #' hclust("sin") %>%
725 #' as.dendrogram()
726 #' dend12 <- dendlist(dend1, dend2)
727 #' # dend12 %>% untangle %>% tanglegram
728 #' dend12 %>% tanglegram(common_subtrees_color_branches = TRUE)
729 #'
730 #'
731 #' set.seed(22133513)
732 #' ss <- sample(1:150, 10)
733 #' dend1 <- iris[ss, -5] %>%
734 #' dist() %>%
735 #' hclust("com") %>%
736 #' as.dendrogram()
737 #' dend2 <- iris[ss, -5] %>%
738 #' dist() %>%
739 #' hclust("sin") %>%
740 #' as.dendrogram()
741 #' dend12 <- dendlist(dend1, dend2)
742 #' # dend12 %>% untangle %>% tanglegram
743 #' dend12 %>% tanglegram(common_subtrees_color_branches = TRUE)
744 #' dend12 %>% tanglegram()
745 #' }
746 tanglegram <- function(dend1, ...) {
747 UseMethod("tanglegram")
748 }
749
750 #' @export
751 #' @rdname tanglegram
752 tanglegram.default <- function(dend1, ...) {
753 stop("No default function for tanglegram - must use a dendrogram/hclust/phylo object")
754 }
755
756 #' @export
757 #' @rdname tanglegram
758 tanglegram.hclust <- function(dend1, ...) {
759 tanglegram.dendrogram(dend1 = dend1, ...)
760 }
761
762 #' @export
763 #' @rdname tanglegram
764 tanglegram.phylo <- function(dend1, ...) {
765 tanglegram.dendrogram(dend1 = dend1, ...)
766 }
767
768 #' @export
769 #' @rdname tanglegram
770 tanglegram.dendlist <- function(dend1, which = c(1L, 2L), main_left, main_right, just_one = TRUE, ...) {
771 # many things can go wrong here (which we might wish to fix):
772 # we could have parameter just_one set to FALSE but no layout predefined, in which case we can't plot
773 if (!just_one & identical(par("mfrow"), c(1, 1))) stop("A layout must be defined when just_one is FALSE")
774 # we could get a dendlist with a length of 1 - in which case, we can't plot
775 if (length(dend1) == 1) stop("Your dendlist has only 1 dendrogram - a tanglegram can not be plotted")
776 # we could get a dendlist with a length of >2 - in which case, should we only plot the first two items?
777 if (all(which %in% seq_len(length(dend1)))) {
778 l1 <- which[1]
779 l2 <- which[2]
780
781 if (!is.null(names(dend1))) {
782 if (missing(main_left)) main_left <- names(dend1)[l1]
783 if (missing(main_right)) main_right <- names(dend1)[l2]
784 } else {
785 if (missing(main_left)) main_left <- ""
786 if (missing(main_right)) main_right <- ""
787 }
788
789 tanglegram.dendrogram(dend1[[l1]], dend1[[l2]], main_left = main_left, main_right = main_right, just_one = just_one, ...)
790 } else {
791 stop("You are trying to plot trees which are outside the range of trees in your dendlist")
792 }
793 }
794
795
796 #' @export
797 #' @rdname tanglegram
798 tanglegram.dendrogram <- function(dend1, dend2, sort = FALSE,
799 color_lines,
800 lwd = 3.5,
801 edge.lwd = NULL,
802 # columns_width = c(5, 2, 3, 2, 5),
803 columns_width = c(5, 3, 5),
804 margin_top = 3,
805 margin_bottom = 2.5,
806 margin_inner = 3,
807 margin_outer = 0.5,
808 left_dendo_mar = c(margin_bottom, margin_outer, margin_top, margin_inner),
809 right_dendo_mar = c(margin_bottom, margin_inner, margin_top, margin_outer),
810 intersecting = TRUE,
811 dLeaf = NULL, # -.3,
812 dLeaf_left = dLeaf,
813 dLeaf_right = dLeaf,
814 axes = TRUE,
815 type = "r", # can also be "t"
816 lab.cex = NULL,
817 remove_nodePar = FALSE,
818 main = "",
819 main_left = "",
820 main_right = "",
821 sub = "",
822 k_labels = NULL,
823 k_branches = NULL,
824 rank_branches = FALSE,
825 hang = FALSE,
826 match_order_by_labels = TRUE,
827 cex_main = 2,
828 cex_main_left = cex_main,
829 cex_main_right = cex_main,
830 cex_sub = cex_main,
831 highlight_distinct_edges = TRUE,
832 common_subtrees_color_lines = TRUE,
833 common_subtrees_color_lines_default_single_leaf_color = "grey",
834 common_subtrees_color_branches = FALSE,
835 highlight_branches_col = FALSE,
836 highlight_branches_lwd = TRUE,
837 faster = FALSE,
838 just_one = TRUE,
839 ...) {
840 if (faster) {
841 highlight_distinct_edges <- FALSE
842 common_subtrees_color_lines <- FALSE
843 common_subtrees_color_branches <- FALSE
844 highlight_branches_lwd <- FALSE
845 }
846
847
848 if (just_one) {
849 # save default, for resetting...
850 def_par <- par(no.readonly = TRUE)
851 }
852
853
854
855 # characters_to_prune = the number of characters to leave after pruning the labels.
856 # remove_nodePar = makes sure that we won't have any dots at the end of leaves
857
858 if (!is.dendrogram(dend1)) dend1 <- as.dendrogram(dend1)
859 if (!is.dendrogram(dend2)) dend2 <- as.dendrogram(dend2)
860
861 # remove colors from the tips of leaves
862 if (remove_nodePar) {
863 dend1 <- remove_leaves_nodePar(dend1)
864 dend2 <- remove_leaves_nodePar(dend2)
865 }
866 # sort them for better graph
867 if (sort == TRUE) { # based on the "rotate.dendrogram" function
868 dend1 <- sort(dend1)
869 dend2 <- sort(dend2)
870 }
871 if (intersecting) {
872 dend12 <- intersect_trees(dend1, dend2, warn = TRUE)
873 dend1 <- dend12[[1]]
874 dend2 <- dend12[[2]]
875 }
876 # adjust labels cex:
877 if (!is.null(lab.cex)) {
878 dend1 <- assign_values_to_leaves_nodePar(dend1, lab.cex, "lab.cex", warn = dendextend_options("warn"))
879 dend2 <- assign_values_to_leaves_nodePar(dend2, lab.cex, "lab.cex", warn = dendextend_options("warn"))
880 }
881 if (!is.null(edge.lwd)) {
882 highlight_branches_lwd <- FALSE # so that it does not override this parameter
883 dend1 <- assign_values_to_branches_edgePar(dend1, edge.lwd, "lwd")
884 dend2 <- assign_values_to_branches_edgePar(dend2, edge.lwd, "lwd")
885 }
886 if (!is.null(k_labels)) {
887 dend1 <- color_labels(dend1, k = k_labels)
888 dend2 <- color_labels(dend2, k = k_labels)
889 }
890 if (!is.null(k_branches)) {
891 dend1 <- color_branches(dend1, k = k_branches)
892 dend2 <- color_branches(dend2, k = k_branches)
893 }
894 if (rank_branches) {
895 dend1 <- rank_branches(dend1)
896 dend2 <- rank_branches(dend2)
897 }
898 # MUST
899 if (hang) {
900 dend1 <- hang.dendrogram(dend1)
901 dend2 <- hang.dendrogram(dend2)
902 }
903
904 if (highlight_distinct_edges) {
905 ##
906 if (!has_edgePar(dend1, "lty")) dend1 <- highlight_distinct_edges(dend1, dend2, edgePar = "lty", value = 3)
907 if (!has_edgePar(dend2, "lty")) dend2 <- highlight_distinct_edges(dend2, dend1, edgePar = "lty", value = 3)
908 }
909
910
911 if (common_subtrees_color_branches) {
912 clusters1 <- common_subtrees_clusters(dend1, dend2)
913 # clusters2 <- common_subtrees_clusters(dend2, dend1)
914 dend1 <- color_branches(dend1, clusters = clusters1)
915 # dend2 <- color_branches(dend2, clusters = clusters2)
916 dend1_leaves_colors <- get_leaves_branches_col(dend1)
917
918 # in cases when lwd is defined, the NAs are not provided and the two vectors
919 # (clusters1 and dend1_leaves_colors) have different lengths.
920 # I repeat this to all cases by removing the NAs. Knowing where they should be,
921 # based on the 0s in clusters1, I am able to fit the colors properly in both cases.
922 dend1_leaves_colors <- as.vector(na.omit(dend1_leaves_colors))
923 tmp <- clusters1
924 tmp[tmp != 0] <- dend1_leaves_colors
925 dend1_leaves_colors <- tmp
926 dend1_leaves_colors[tmp == 0] <- "black"
927
928 # match_1_to_be_2
929 ss <- match(labels(dend2), labels(dend1))
930 # labels(dend1)[ss]
931 # labels(dend2)
932 the_leaves_colors <- dend1_leaves_colors[ss]
933 # the_leaves_colors[is.na(the_leaves_colors)] <- 1
934 dend2_clusters <- rank_values_with_clusters(clusters1[ss], ignore0 = TRUE)
935 dend2 <- branches_attr_by_clusters(dend2, dend2_clusters,
936 values = the_leaves_colors, attr = "col",
937 branches_changed_have_which_labels = "all"
938 )
939
940 # tanglegram(dend1,dend2)
941 # a <- clusters1[ss]
942 # a[c(1,2,6)] <- 4:6
943 # b <- dend1_leaves_colors[ss]
944 # b[is.na(b)] <- "black"
945 # branches_attr_by_clusters(dend2, a,
946 # values = b, attr = "col")
947
948
949
950 # If I know I am using the common_subtrees_color_branches
951 # I might as well match them to the lines:
952 if (common_subtrees_color_lines) {
953 color_lines <- dend1_leaves_colors
954 color_lines[is.na(color_lines)] <- common_subtrees_color_lines_default_single_leaf_color
955 }
956 }
957
958 # if we didn't resolve color_lines yet - let's figure it out now:
959 if (missing(color_lines)) {
960 if (common_subtrees_color_lines) {
961 # color_lines <- rep("black", nleaves(dend1))
962 # lines_color_clusters <- common_subtrees_clusters(dend1, dend2, leaves_get_0_cluster = TRUE)
963 # ss_not_0s <- lines_color_clusters != 0
964 # colors_for_lines_color <- lines_color_clusters[ss_not_0s] %>% unique %>% length %>% rainbow_fun
965 # color_lines[ss_not_0s] <- colors_for_lines_color[lines_color_clusters[ss_not_0s]]
966
967 lines_color_clusters <- common_subtrees_clusters(dend1, dend2, leaves_get_0_cluster = FALSE)
968 colors_for_lines_color <- lines_color_clusters %>%
969 unique() %>%
970 length() %>%
971 rainbow_fun()
972 color_lines <- colors_for_lines_color[lines_color_clusters]
973
974 ss_0s <- replace_unique_items_with_0_and_rank(lines_color_clusters) == 0
975 color_lines[ss_0s] <- common_subtrees_color_lines_default_single_leaf_color
976 } else {
977 color_lines <- "darkgrey"
978 }
979 }
980
981 if (highlight_branches_col) {
982 if (!has_edgePar(dend1, "col")) dend1 <- highlight_branches_col(dend1)
983 if (!has_edgePar(dend2, "col")) dend2 <- highlight_branches_col(dend2)
984 }
985 if (highlight_branches_lwd) {
986 if (!has_edgePar(dend1, "lwd")) dend1 <- highlight_branches_lwd(dend1)
987 if (!has_edgePar(dend2, "lwd")) dend2 <- highlight_branches_lwd(dend2)
988 }
989
990
991 l <- nleaves(dend1)
992
993 # makes sure that dLeaf gives a symmetric result.
994 if (!is.null(dLeaf) && dLeaf_right == dLeaf_left) {
995 dLeaf_right <- -dLeaf_left
996 }
997
998 ##########################################
999 ##### Plotting.
1000 ##########################################
1001
1002 labels_dend1 <- labels(dend1)
1003 max_labels_dend1 <- labels_dend1[which.max(nchar(labels_dend1))]
1004
1005
1006 # The matrix to draw the arrows:
1007 if (match_order_by_labels) dend1 <- match_order_by_labels(dend1, dend2)
1008 ord_arrow <- cbind((1:l)[order(order.dendrogram(dend1))], (1:l)[order(order.dendrogram(dend2))])
1009
1010 # Set the layout of the plot elements
1011 if (just_one) layout(matrix(1:3, nrow = 1), widths = columns_width)
1012
1013 #################
1014 # The first dendrogram:
1015 #################
1016 par(mar = left_dendo_mar)
1017 plot(dend1,
1018 horiz = TRUE, ylim = c(0, l),
1019 dLeaf = dLeaf_left,
1020 type = type, axes = axes,
1021 main = main_left,
1022 cex.main = cex_main_left,
1023 # ...)
1024 # leaflab="none",
1025 yaxs = "r", xaxs = "i", ...
1026 ) # this might be causing bugs when refreshing a resized window.
1027
1028 # now that I have a plot to use, I can calculate strwidth
1029 # this ASSUMES that both tree plots are of the same size/shape...
1030
1031 #################
1032 # The arrows:
1033 #################
1034 # arros colors:
1035 if (length(color_lines) < l) color_lines <- rep.int(color_lines, l)
1036 color_lines <- color_lines[ord_arrow[, 1]]
1037
1038 par(mar = c(margin_bottom, 0, margin_top, 0))
1039 plot(NA,
1040 bty = "n", axes = FALSE, xlim = c(0, 1), ylim = c(0, l), ylab = "", xlab = "", # )#,
1041 yaxs = "r", xaxs = "i"
1042 )
1043 col_indx <- 0
1044 apply(
1045 ord_arrow, 1,
1046 function(x) {
1047 col_indx <<- col_indx + 1
1048 arrows(0, x[1], 1, x[2], code = 0, length = 0.05, col = color_lines[col_indx], lwd = lwd)
1049 }
1050 )
1051 mtext(main, side = 3, cex = cex_main)
1052 mtext(sub, side = 1, cex = cex_sub)
1053
1054 #################
1055 # And the second dendrogram (to reverse it I reversed the xlim vector:
1056 #################
1057 par(mar = right_dendo_mar)
1058 plot_horiz.dendrogram(dend2,
1059 side = TRUE, dLeaf = dLeaf_right,
1060 type = type, axes = axes,
1061 ylim = c(0, l),
1062 cex.main = cex_main_left,
1063 main = main_right,
1064 # ...)
1065 # leaflab="none",
1066 yaxs = "r", xaxs = "i", ...
1067 )
1068
1069 # layout(matrix(1)) # not required
1070
1071 if (just_one) {
1072 par(def_par) #- reset to default
1073 }
1074
1075
1076
1077 return(invisible(dendlist(dend1 = dend1, dend2 = dend2)))
1078 }
1079
1080
1081
1082 # add an "abbreviation" parameter - to prune the labels of two trees.
1083
1084
1085
1086 #' @export
1087 #' @rdname tanglegram
1088 dendbackback <- tanglegram.dendrogram # another name for the same function.
1089 # hclustbackback <- tanglegram.hclust # another name for the same function.