Debian Codegraph @

inst/doc/dendextend.Rmd

raw
1 ---
2 title: "Introduction to dendextend"
3 date: "`r Sys.Date()`"
4 author: "Tal Galili"
5 output:
6 html_vignette:
7 self_contained: yes
8 toc: true
9 editor_options:
10 chunk_output_type: console
11 ---
12 <!--
13 %\VignetteEngine{knitr::rmarkdown}
14 %\VignetteIndexEntry{Introduction to dendextend}
15 -->
16
17
18 ```{r, echo = FALSE, message = FALSE}
19 library(dendextend)
20 library(knitr)
21 knitr::opts_chunk$set(
22 cache = TRUE,
23 dpi = 75,
24 fig.width = 6, fig.height = 6,
25 comment = "#>",
26 tidy = FALSE)
27
28 # https://stackoverflow.com/questions/24091735/why-pandoc-does-not-retrieve-the-image-file
29 # < ! -- rmarkdown v1 -->
30
31 ```
32
33
34 **Author**: Tal Galili (homepage: r-statistics.com, e-mail: [email protected] )
35
36 **tl;dr**: the [_dendextend package_](https://cran.r-project.org/package=dendextend) let's you create figures like this:
37
38
39
40
41 ```{r, echo=FALSE, warning=FALSE, fig.align='center', fig.width=7, fig.height=7}
42 suppressMessages(library(dendextend))
43 library(colorspace)
44
45 dend1 <- c(1:5) %>% # take some data
46 dist %>% # calculate a distance matrix,
47 hclust(method = "average") %>% # on it compute hierarchical clustering using the "average" method,
48 as.dendrogram # and lastly, turn that object into a dendrogram.
49 dend2 <- c(1:5) %>% # take some data
50 dist %>% # calculate a distance matrix,
51 hclust(method = "single") %>% # on it compute hierarchical clustering using the "average" method,
52 as.dendrogram # and lastly, turn that object into a dendrogram.
53 dend1 <- rotate(dend1, order = c(as.character(5:1)))
54 labels(dend1) <- rev(c("dendextend", "let's u easily", "control","(and compare) your", "dendrograms"))
55 labels(dend2) <- rev(c("let's u easily","dendextend" ,"control","(and compare) your", "dendrograms"))
56 dend1 <- dend1 %>%
57 color_labels %>%
58 set("labels_cex", c(2.2,1.4)) %>%
59 set("branches_lwd", c(4,1,4)) %>%
60 set("branches_lty", c(1,2,1)) %>%
61 set("nodes_pch", c(NA,19,NA)) %>%
62 set("nodes_cex", c(NA,2.5,NA)) %>%
63 set("nodes_col", c(NA,3,NA)) %>%
64 hang.dendrogram # %>% plot
65 dend2 <- color_branches(dend2)
66 # dend2 <- color_labels(dend2)
67 tanglegram(dendlist(dend1, dend2), margin_inner = 9,
68 color_lines = c(rep("darkgreen", 3) , rep("darkred",2)),
69 sub= paste("Entanglement:", round(entanglement(dendlist(dend1, dend2)),2)), cex_sub = 1.5
70 )
71
72 # dend2 %>% color_branches %>% plot
73 # dend2 %>% color_branches(k=3) %>% plot # nice, returns the tree as is...
74 # dend2 %>% color_labels %>% plot
75 # cutree(dend2,3)
76
77
78 ```
79
80
81
82
83 Introduction
84 --------------
85
86 The [**_dendextend package_**](https://cran.r-project.org/package=dendextend) offers a set of functions for extending dendrogram objects in R, letting you **visualize** and **compare** trees of hierarchical clusterings, you can:
87
88 * **Adjust a tree's graphical parameters** - the color, size, type, etc of its branches, nodes and labels.
89 * Visually and statistically **compare different dendrograms** to one another.
90
91 The goal of this document is to introduce you to the basic functions that dendextend provides, and show how they may be applied. We will make extensive use of "chaining" (explained next).
92
93
94
95
96 Prerequisites
97 --------------
98
99 ### Acknowledgement
100
101 This package was made possible by the the support of my thesis adviser [Yoav Benjamini](http://www.math.tau.ac.il/~ybenja/), as well as code contributions from many R users. They are:
102
103 ```{r, echo=FALSE}
104
105 c(person("Tal", "Galili", role = c("aut", "cre", "cph"), email =
106 "[email protected]", comment = "https://www.r-statistics.com"),
107 person("Gavin", "Simpson", role = "ctb"), person("Gregory","Jefferis", role
108 = "ctb", email = "[email protected]",
109 comment ="imported code from his dendroextras package"),
110 person("Marco", "Gallotta", role = "ctb", comment =
111 "a.k.a: marcog") , person("Johan", "Renaudie", role = "ctb", comment =
112 "https://github.com/plannapus"), person("R core team", role = "ctb",
113 comment = "Thanks for the Infastructure, and code in the examples"),
114 person("Kurt", "Hornik", role = "ctb"), person("Uwe", "Ligges",
115 role = "ctb"), person("Andrej-Nikolai", "Spiess", role = "ctb"),
116 person("Steve", "Horvath",email = "[email protected]", role =
117 "ctb"), person("Peter", "Langfelder",email = "[email protected]",
118 role = "ctb"), person("skullkey", role = "ctb"), person("Mark",
119 "Van Der Loo", email = "[email protected]", comment =
120 "https://github.com/markvanderloo d3dendrogram", role = "ctb"),
121 person("Yoav", "Benjamini", role = "ths"))
122
123 ```
124
125
126 The **design** of the dendextend package (and this manual!) is heavily inspired by [Hadley Wickham's](https://hadley.nz/) work. Especially his text on [writing an R package](https://r-pkgs.org/), the [devtools package](https://cran.r-project.org/package=devtools), and the dplyr package (specifically the use of chaining, and the [Introduction text to dplyr](https://CRAN.R-project.org/package=dplyr/vignettes/dplyr.html)).
127
128
129
130
131 ### Chaining
132
133 Function calls in dendextend often get a dendrogram and returns a (modified) dendrogram. This doesn't lead to particularly elegant code if you want to do many operations at once. The same is true even in the first stage of creating a dendrogram.
134
135 In order to construct a dendrogram, you will (often) need to go through several steps. You can either do so while keeping the intermediate results:
136
137 ```{r, eval = FALSE}
138 d1 <- c(1:5) # some data
139 d2 <- dist(d1)
140 d3 <- hclust(d2, method = "average")
141 dend <- as.dendrogram(d3)
142 ```
143
144 Or, you can also wrap the function calls inside each other:
145
146 ```{r, eval=FALSE}
147 dend <- as.dendrogram(hclust(dist(c(1:5)), method = "average"))
148 ```
149
150 However, both solutions are not ideal: the first solution includes redundant intermediate objects, while the second is difficult to read (since the order of the operations is from inside to out, while the arguments are a long way away from the function).
151
152 To get around this problem, dendextend encourages the use of the `%>%` ("pipe" or "chaining") operator (imported from the magrittr package). This turns `x %>% f(y)` into `f(x, y)` so you can use it to rewrite ("chain") multiple operations such that they can be read from left-to-right, top-to-bottom.
153
154 For example, the following will be written as it would be explained:
155
156 ```{r, eval = FALSE}
157 dend <- c(1:5) %>% # take the a vector from 1 to 5
158 dist %>% # calculate a distance matrix,
159 hclust(method = "average") %>% # on it compute hierarchical clustering using the "average" method,
160 as.dendrogram # and lastly, turn that object into a dendrogram.
161 ```
162
163 For more details, you may look at:
164
165 * [magrittr on CRAN](https://cran.r-project.org/package=magrittr)
166 * [Introduction to the magrittr package](https://CRAN.R-project.org/package=magrittr/vignettes/magrittr.html)
167 * [Simpler R coding with pipes > the present and future of the magrittr package](https://www.r-statistics.com/2014/08/simpler-r-coding-with-pipes-the-present-and-future-of-the-magrittr-package/)
168
169 ### A dendrogram is a nested list of lists with attributes
170
171 The first step is working with dendrograms, is to understand that they are just a **nested list of lists with attributes**. Let us explore this for the following (tiny) tree:
172
173 ```{r, fig.width=4, fig.height=3}
174 # Create a dend:
175 dend <- 1:2 %>% dist %>% hclust %>% as.dendrogram
176 # and plot it:
177 dend %>% plot
178 ```
179
180 And here is its structure (a nested list of lists with attributes):
181
182 ```{r}
183 dend %>% unclass %>% str
184 dend %>% class
185 ```
186
187
188
189
190
191 ### Installation
192
193 To install the stable version on CRAN use:
194
195 ```r
196 install.packages('dendextend')
197 ```
198
199 To install the GitHub version:
200
201 ```R
202 require2 <- function (package, ...) {
203 if (!require(package)) install.packages(package); library(package)
204 }
205
206 ## require2('installr')
207 ## install.Rtools() # run this if you are using Windows and don't have Rtools installed
208
209 # Load devtools:
210 require2("devtools")
211 devtools::install_github('talgalili/dendextend')
212 <!-- require2("Rcpp") -->
213
214 # Having colorspace is also useful, since it is used
215 # In various examples in the vignettes
216 require2("colorspace")
217 ```
218
219 And then you may load the package using:
220 ```R
221 library(dendextend)
222 ```
223
224
225
226
227 How to explore a dendrogram's parameters
228 ---------------------------------------
229
230 ### Taking a first look at a dendrogram
231
232 For the following simple tree:
233
234 ```{r, fig.width=4, fig.height=3}
235 # Create a dend:
236 dend <- 1:5 %>% dist %>% hclust %>% as.dendrogram
237 # Plot it:
238 dend %>% plot
239 ```
240
241 Here are some basic parameters we can get:
242
243 ```{r}
244 dend %>% labels # get the labels of the tree
245 dend %>% nleaves # get the number of leaves of the tree
246 dend %>% nnodes # get the number of nodes in the tree (including leaves)
247 dend %>% head # A combination of "str" with "head"
248 ```
249
250 Next let us look at more sophisticated outputs.
251
252 ### Getting nodes attributes in a depth-first search
253
254 When extracting (or inserting) attributes from a dendrogram's nodes, it is often in a "depth-first search". [Depth-first search](https://en.wikipedia.org/wiki/Depth-first_search) is when an algorithm for traversing or searching tree or graph data structures. One starts at the root and explores as far as possible along each branch before backtracking.
255
256 Here is a plot of a tree, illustrating the order in which you should read the "nodes attributes":
257
258 ```{r, echo=FALSE, fig.height=5}
259 # Create a dend:
260 dend <- 1:5 %>% dist %>% hclust %>% as.dendrogram
261
262 # get_nodes_xy(dend)
263 # polygon(get_nodes_xy(dend), col = 2)
264 plot(dend,
265 leaflab = "none", # axes = FALSE, # no labels or y axis
266 main = "Nodes order when using \nDepth-first search in a dendrogram")
267 xy <- get_nodes_xy(dend)
268 for(i in 1:(nrow(xy)-1)) {
269 arrows(xy[i,1], xy[i,2], angle = 17,
270 length = .3,
271 xy[i+1,1], xy[i+1,2],
272 lty = 1, col = 3, lwd = 1.5)
273 }
274 points(xy, pch = 19, cex = 3)
275 text(xy, labels = 1:nnodes(dend),cex = 1.2, col = "white") #, adj = c(0.4,0.4))
276 ```
277
278 We can get several nodes attributes using `get_nodes_attr` (notice the order corresponds with what is shown in the above figure):
279
280 ```{r}
281 # Create a dend:
282 dend <- 1:5 %>% dist %>% hclust %>% as.dendrogram
283 # Get various attributes
284 dend %>% get_nodes_attr("height") # node's height
285 dend %>% hang.dendrogram %>% get_nodes_attr("height") # node's height (after raising the leaves)
286 dend %>% get_nodes_attr("members") # number of members (leaves) under that node
287 dend %>% get_nodes_attr("members", id = c(2,5)) # number of members for nodes 2 and 5
288 dend %>% get_nodes_attr("midpoint") # how much "left" is this node from its left-most child's location
289 dend %>% get_nodes_attr("leaf") # is this node a leaf
290 dend %>% get_nodes_attr("label") # what is the label on this node
291 dend %>% get_nodes_attr("nodePar") # empty (for now...)
292 dend %>% get_nodes_attr("edgePar") # empty (for now...)
293 ```
294
295 A similar function for leaves only is `get_leaves_attr`
296
297
298 How to change a dendrogram
299 ------------------------------------
300
301
302 ### The "set" function
303
304
305 The fastest way to start changing parameters with dendextend is by using the `set` function. It is written as: `set(object, what, value)`, and accepts the following parameters:
306
307 1. **object**: a dendrogram object,
308 2. **what**: a character indicating what is the property of the tree that should be set/updated
309 3. **value**: a vector with the value to set in the tree (the type of the value depends on the "what"). Many times, vectors which are too short are recycled.
310
311 The **what** parameter accepts many options, each uses some general function in the background. These options deal with labels, nodes and branches. They are:
312
313 * labels - set the labels (using `labels<-.dendrogram`)
314 * labels_colors - set the labels' colors (using `color_labels`)
315 * labels_cex - set the labels' size (using `assign_values_to_leaves_nodePar`)
316 * labels_to_character - set the labels' to be characters
317 * leaves_pch - set the leaves' point type (using `assign_values_to_leaves_nodePar`)
318 * leaves_cex - set the leaves' point size (using `assign_values_to_leaves_nodePar`)
319 * leaves_col - set the leaves' point color (using `assign_values_to_leaves_nodePar`)
320 * leaves_bg - set the leaves’ point background color (available only for pch 21-25, using `assign_values_to_nodes_nodePar`)
321 * nodes_pch - set the nodes' point type (using `assign_values_to_nodes_nodePar`)
322 * nodes_cex - set the nodes' point size (using `assign_values_to_nodes_nodePar`)
323 * nodes_col - set the nodes' point color (using `assign_values_to_nodes_nodePar`)
324 * nodes_bg - set the nodes’ point background color (available only for pch 21-25, using `assign_values_to_nodes_nodePar`)
325 * hang_leaves - hang the leaves (using `hang.dendrogram`)
326 * branches_k_color - color the branches (using `color_branches`)
327 * branches_col - set the color of branches (using `assign_values_to_branches_edgePar`)
328 * branches_lwd - set the line width of branches (using `assign_values_to_branches_edgePar`)
329 * branches_lty - set the line type of branches (using `assign_values_to_branches_edgePar`)
330 * by_labels_branches_col - set the color of branches with specific labels (using `branches_attr_by_labels`)
331 * by_labels_branches_lwd - set the line width of branches with specific labels (using `branches_attr_by_labels`)
332 * by_labels_branches_lty - set the line type of branches with specific labels (using `branches_attr_by_labels`)
333 * clear_branches - clear branches' attributes (using `remove_branches_edgePar`)
334 * clear_leaves - clear leaves' attributes (using `remove_branches_edgePar`)
335
336
337 ### Two simple trees to play with
338
339 For illustration purposes, we will create several small tree, and demonstrate these functions on them.
340
341 ```{r, fig.show='hold', fig.width=8, fig.height=3}
342 dend13 <- c(1:3) %>% # take some data
343 dist %>% # calculate a distance matrix,
344 hclust(method = "average") %>% # on it compute hierarchical clustering using the "average" method,
345 as.dendrogram # and lastly, turn that object into a dendrogram.
346 # same, but for 5 leaves:
347 dend15 <- c(1:5) %>% dist %>% hclust(method = "average") %>% as.dendrogram
348
349 par(mfrow = c(1,2))
350 dend13 %>% plot(main="dend13")
351 dend15 %>% plot(main="dend15")
352 # we could have also used plot(dend)
353 ```
354
355
356 ### Setting a dendrogram's labels
357
358 We can get a vector with the tree's labels:
359
360 ```{r}
361 # get the labels:
362 dend15 %>% labels
363 # this is just like labels(dend)
364 ```
365
366 Notice how the tree's labels are not 1 to 5 by order, since the tree happened to place them in a different order. We can change the names of the labels:
367
368 ```{r}
369 # change the labels, and then print them:
370 dend15 %>% set("labels", c(111:115)) %>% labels
371 # could also be done using:
372 # labels(dend) <- c(111:115)
373 ```
374
375 We can change the type of labels to be characters. Not doing so may be a source of various bugs and problems in many functions.
376
377 ```{r}
378 dend15 %>% labels
379 dend15 %>% set("labels_to_char") %>% labels
380 ```
381
382
383 We may also change their color and size:
384
385 ```{r, fig.width=8, fig.height=3}
386 par(mfrow = c(1,2))
387 dend15 %>% set("labels_col", "blue") %>% plot(main = "Change label's color") # change color
388 dend15 %>% set("labels_cex", 2) %>% plot(main = "Change label's size") # change color
389 ```
390
391 The function recycles, from left to right, the vector of values we give it. We can use this to create more complex patterns:
392
393 ```{r, fig.width=8, fig.height=3}
394 # Produce a more complex dendrogram:
395 dend15_2 <- dend15 %>%
396 set("labels", c(111:115)) %>% # change labels
397 set("labels_col", c(1,2,3)) %>% # change color
398 set("labels_cex", c(2,1)) # change size
399
400 par(mfrow = c(1,2))
401 dend15 %>% plot(main = "Before")
402 dend15_2 %>% plot(main = "After")
403 ```
404
405 Notice how these "labels parameters" are nested within the nodePar attribute:
406
407 ```{r}
408 # looking at only the left-most node of the "after tree":
409 dend15_2[[1]][[1]] %>% unclass %>% str
410 # looking at only the nodePar attributes in this sub-tree:
411 dend15_2[[1]][[1]] %>% get_nodes_attr("nodePar")
412 ```
413
414 When it comes to color, we can also set the parameter "k", which will cut the tree into k clusters, and assign a different color to each label (based on its cluster):
415
416 ```{r, fig.width=8, fig.height=3}
417 par(mfrow = c(1,2))
418 dend15 %>% set("labels_cex", 2) %>% set("labels_col", value = c(3,4)) %>%
419 plot(main = "Recycles color \nfrom left to right")
420 dend15 %>% set("labels_cex", 2) %>% set("labels_col", value = c(3,4), k=2) %>%
421 plot(main = "Color labels \nper cluster")
422 abline(h = 2, lty = 2)
423 ```
424
425
426 ### Setting a dendrogram's nodes/leaves (points)
427
428 Each node in a tree can be represented and controlled using the `assign_values_to_nodes_nodePar`, and for the special case of the nodes of leaves, the `assign_values_to_leaves_nodePar` function is more appropriate (and faster) to use. We can control the following properties: pch (point type), cex (point size), and col (point color). For pch we can additionally set bg ("background", although it's really a fill for the shape). When bg is set, the outline of the point is defined by col and the internal fill is determined by bg. For example:
429
430 ```{r, fig.width=10, fig.height=6}
431 par(mfrow = c(2,3))
432 dend13 %>% set("nodes_pch", 19) %>% plot(main = "(1) Show the\n nodes (as a dot)") #1
433 dend13 %>% set("nodes_pch", 19) %>% set("nodes_cex", 2) %>%
434 plot(main = "(2) Show (larger)\n nodes") #2
435 dend13 %>% set("nodes_pch", 19) %>% set("nodes_cex", 2) %>% set("nodes_col", 3) %>%
436 plot(main = "(3) Show (larger+colored)\n nodes") #3
437
438 dend13 %>% set("leaves_pch", 21) %>% plot(main = "(4) Show the leaves\n (as empty circles)") #4
439 dend13 %>% set("leaves_pch", 21) %>% set("leaves_cex", 2) %>%
440 plot(main = "(5) Show (larger)\n leaf circles") #5
441 dend13 %>%
442 set("leaves_pch", 21) %>%
443 set("leaves_bg", "gold") %>%
444 set("leaves_cex", 2) %>%
445 set("leaves_col", "darkred") %>%
446 plot(main = "(6) Show (larger+colored+filled)\n leaves") #6
447
448 ```
449
450 And with recycling we can produce more complex outputs:
451
452 ```{r, fig.width=8, fig.height=4}
453 par(mfrow = c(1,2))
454 dend15 %>% set("nodes_pch", c(19,1,4)) %>% set("nodes_cex", c(2,1,2)) %>% set("nodes_col", c(3,4)) %>%
455 plot(main = "Adjust nodes")
456 dend15 %>% set("leaves_pch", c(19,1,4)) %>% set("leaves_cex", c(2,1,2)) %>% set("leaves_col", c(3,4)) %>%
457 plot(main = "Adjust nodes\n(but only for leaves)")
458 ```
459
460 Notice how recycling works in a depth-first order (which is just left to right, when we only adjust the leaves). Here are the node's parameters after adjustment:
461
462 ```{r}
463 dend15 %>% set("nodes_pch", c(19,1,4)) %>%
464 set("nodes_cex", c(2,1,2)) %>% set("nodes_col", c(3,4)) %>% get_nodes_attr("nodePar")
465 ```
466
467 We can also change the height of of the leaves by using the `hang.dendrogram` function:
468
469 ```{r, fig.width=10, fig.height=3}
470 par(mfrow = c(1,3))
471 dend13 %>% set("leaves_pch", 19) %>% set("leaves_cex", 2) %>% set("leaves_col", 2) %>% # adjust the leaves
472 hang.dendrogram %>% # hang the leaves
473 plot(main = "Hanging a tree")
474 dend13 %>% set("leaves_pch", 19) %>% set("leaves_cex", 2) %>% set("leaves_col", 2) %>% # adjust the leaves
475 hang.dendrogram(hang_height = .6) %>% # hang the leaves (at some height)
476 plot(main = "Hanging a tree (but lower)")
477 dend13 %>% set("leaves_pch", 19) %>% set("leaves_cex", 2) %>% set("leaves_col", 2) %>% # adjust the leaves
478 hang.dendrogram %>% # hang the leaves
479 hang.dendrogram(hang = -1) %>% # un-hanging the leaves
480 plot(main = "Not hanging a tree")
481 ```
482
483 An example of what this function does to the leaves heights:
484
485 ```{r}
486 dend13 %>% get_leaves_attr("height")
487 dend13 %>% hang.dendrogram %>% get_leaves_attr("height")
488 ```
489
490 We can also control the general heights of nodes using `raise.dendrogram`:
491
492 ```{r, fig.width=10, fig.height=3}
493 par(mfrow = c(1,3))
494 dend13 %>% plot(main = "First tree", ylim = c(0,3))
495 dend13 %>%
496 raise.dendrogram (-1) %>%
497 plot(main = "One point lower", ylim = c(0,3))
498 dend13 %>%
499 raise.dendrogram (1) %>%
500 plot(main = "One point higher", ylim = c(0,3))
501 ```
502
503 If you wish to make the branches under the root have the same height, you can use the `flatten.dendrogram` function.
504
505 ### Setting a dendrogram's branches
506
507
508 #### Adjusting all branches
509
510 Similar to adjusting nodes, we can also control line width (lwd), line type (lty), and color (col) for branches:
511
512 ```{r, fig.width=10, fig.height=3}
513 par(mfrow = c(1,3))
514 dend13 %>% set("branches_lwd", 4) %>% plot(main = "Thick branches")
515 dend13 %>% set("branches_lty", 3) %>% plot(main = "Dashed branches")
516 dend13 %>% set("branches_col", 2) %>% plot(main = "Red branches")
517 ```
518
519 We may also use recycling to create more complex patterns:
520
521 ```{r, fig.width=4, fig.height=3}
522 # Produce a more complex dendrogram:
523 dend15 %>%
524 set("branches_lwd", c(4,1)) %>%
525 set("branches_lty", c(1,1,3)) %>%
526 set("branches_col", c(1,2,3)) %>%
527 plot(main = "Complex branches", edge.root = TRUE)
528 ```
529
530 Notice how the first branch (the root) is considered when going through and creating the tree, but it is **ignored** in the actual plotting (this is actually a "missing feature" in `plot.dendrogram`).
531
532 #### Coloring branches based on clustering
533
534 We may also control the colors of the branches based on using clustering:
535
536 ```{r, fig.width=8, fig.height=3}
537 par(mfrow = c(1,2))
538 dend15 %>% set("branches_k_color", k = 3) %>% plot(main = "Nice defaults")
539 dend15 %>% set("branches_k_color", value = 3:1, k = 3) %>%
540 plot(main = "Controlling branches' colors\n(via clustering)")
541 # This is like using the `color_branches` function
542 ```
543
544
545
546 #### Adjusting branches based on labels
547
548 The most powerful way to control branches is through the `branches_attr_by_labels` function (with variations through the `set` function). The function allows you to change col/lwd/lty of branches if they match some "labels condition". Follow carefully:
549
550
551 ```{r, fig.width=8, fig.height=3}
552 par(mfrow = c(1,2))
553 dend15 %>% set("by_labels_branches_col", value = c(1,4)) %>%
554 plot(main = "Adjust the branch\n if ALL (default) of its\n labels are in the list")
555 dend15 %>% set("by_labels_branches_col", value = c(1,4), type = "any") %>%
556 plot(main = "Adjust the branch\n if ANY of its\n labels are in the list")
557 ```
558
559 We can use this to change the size/type/color of the branches:
560
561 ```{r, fig.width=10, fig.height=3}
562 # Using "Inf" in "TF_values" means to let the parameters stay as they are.
563 par(mfrow = c(1,3))
564 dend15 %>% set("by_labels_branches_col", value = c(1,4), TF_values = c(3,Inf)) %>%
565 plot(main = "Change colors")
566 dend15 %>% set("by_labels_branches_lwd", value = c(1,4), TF_values = c(8,1)) %>%
567 plot(main = "Change line width")
568 dend15 %>% set("by_labels_branches_lty", value = c(1,4), TF_values = c(3,Inf)) %>%
569 plot(main = "Change line type")
570 ```
571
572
573
574 #### Highlighting branches' different heights using line width and color
575
576
577 The `highlight_branches` function helps to more easily see the topological structure of a tree, by adjusting branches appearence (color and line width) based on their height in the tree. For example:
578
579
580
581 ```{r, fig.width=8, fig.height=3}
582
583 dat <- iris[1:20,-5]
584 hca <- hclust(dist(dat))
585 hca2 <- hclust(dist(dat), method = "single")
586 dend <- as.dendrogram(hca)
587 dend2 <- as.dendrogram(hca2)
588
589 par(mfrow = c(1,3))
590 dend %>% highlight_branches_col %>% plot(main = "Coloring branches")
591 dend %>% highlight_branches_lwd %>% plot(main = "Emphasizing line-width")
592 dend %>% highlight_branches %>% plot(main = "Emphasizing color\n and line-width")
593
594 ```
595
596 Tanglegrams are even easier to compare when using
597
598
599
600 ```{r, fig.width=8, fig.height=4}
601
602 library(viridis)
603 par(mfrow = c(1,3))
604 dend %>% highlight_branches_col %>% plot(main = "Coloring branches \n (default is reversed viridis)")
605 dend %>% highlight_branches_col(viridis(100)) %>% plot(main = "It is better to use \n lighter colors in the leaves")
606 dend %>% highlight_branches_col(rev(magma(1000))) %>% plot(main = "The magma color pallatte\n is also good")
607
608 dl <- dendlist(dend, dend2)
609 tanglegram(dl, sort = TRUE, common_subtrees_color_lines = FALSE, highlight_distinct_edges = FALSE, highlight_branches_lwd = FALSE)
610 tanglegram(dl)
611 tanglegram(dl, fast = TRUE)
612
613 dl <- dendlist(highlight_branches(dend), highlight_branches(dend2))
614 tanglegram(dl, sort = TRUE, common_subtrees_color_lines = FALSE, highlight_distinct_edges = FALSE)
615
616 # dend %>% set("highlight_branches_col") %>% plot
617
618 dl <- dendlist(dend, dend2) %>% set("highlight_branches_col")
619 tanglegram(dl, sort = TRUE, common_subtrees_color_lines = FALSE, highlight_distinct_edges = FALSE)
620
621 ```
622
623
624
625 ### Changing a dendrogram's structure
626
627
628 #### Rotation
629
630 A dendrogram is an object which can be rotated on its hinges without changing its topology.
631 Rotating a dendrogram in base R can be done using the `reorder` function. The problem with
632 this function is that it is not very intuitive. For this reason the `rotate` function was written.
633 It has two main arguments: the "object" (a dendrogram), and the "order" we wish to rotate it by. The "order" parameter can be either a numeric vector, used in a similar way we would order a simple
634 character vector. Or, the order parameter can also be a character vector of the labels of the
635 tree, given in the new desired order of the tree.
636 It is also worth noting that some order are impossible to achieve for a given tree's topology. In such cases, the function will do its "best" to get as close as possible to the requested rotation.
637
638
639 ```{r, fig.width=10, fig.height=3}
640 par(mfrow = c(1,3))
641 dend15 %>%
642 set("labels_colors") %>%
643 set("branches_k_color") %>%
644 plot(main = "First tree")
645 dend15 %>%
646 set("labels_colors") %>%
647 set("branches_k_color") %>%
648 rotate(as.character(5:1)) %>% #rotate to match labels new order
649 plot(main = "Rotated tree\n based on labels")
650 dend15 %>%
651 set("labels_colors") %>%
652 set("branches_k_color") %>%
653 rotate(5:1) %>% # the fifth label to go first is "4"
654 plot(main = "Rotated tree\n based on order")
655 ```
656
657
658 A new convenience S3 function for `sort` (`sort.dendrogram`) was added:
659
660 ```{r, fig.width=12, fig.height=6}
661 dend110 <- c(1, 3:5, 7,9,10) %>% dist %>% hclust(method = "average") %>%
662 as.dendrogram %>% color_labels %>% color_branches
663
664 par(mfrow = c(1,3))
665 dend110 %>% plot(main = "Original tree")
666 dend110 %>% sort %>% plot(main = "labels sort")
667 dend110 %>% sort(type = "nodes") %>% plot(main = "nodes (ladderize) sort")
668 ```
669
670
671
672
673
674 #### Unbranching
675
676
677 We can unbranch a tree:
678
679 ```{r, fig.width=10, fig.height=3}
680 par(mfrow = c(1,3))
681 dend15 %>% plot(main = "First tree", ylim = c(0,3))
682 dend15 %>%
683 unbranch %>%
684 plot(main = "Unbranched tree", ylim = c(0,3))
685 dend15 %>%
686 unbranch(2) %>%
687 plot(main = "Unbranched tree (2)", ylim = c(0,3))
688 ```
689
690
691 #### Pruning
692
693 We can prune a tree based on the labels:
694
695 ```{r, fig.width=7, fig.height=3}
696 par(mfrow = c(1,2))
697 dend15 %>% set("labels_colors") %>%
698 plot(main = "First tree", ylim = c(0,3))
699 dend15 %>% set("labels_colors") %>%
700 prune(c("1","5")) %>%
701 plot(main = "Prunned tree", ylim = c(0,3))
702 ```
703
704 For pruning two trees to have matching labels, we can use the `intersect_trees` function:
705
706 ```{r, fig.width=7, fig.height=3}
707 par(mfrow = c(1,2))
708 dend_intersected <- intersect_trees(dend13, dend15)
709 dend_intersected[[1]] %>% plot
710 dend_intersected[[2]] %>% plot
711 ```
712
713
714 #### Collapse branches
715
716 We can collapse branches under a tolerance level using the `collapse_branch` function:
717
718 ```{r}
719 # ladderize is like sort(..., type = "node")
720 dend <- iris[1:5,-5] %>% dist %>% hclust %>% as.dendrogram
721 par(mfrow = c(1,3))
722 dend %>% ladderize %>% plot(horiz = TRUE); abline(v = .2, col = 2, lty = 2)
723 dend %>% collapse_branch(tol = 0.2) %>% ladderize %>% plot(horiz = TRUE)
724 dend %>% collapse_branch(tol = 0.2) %>% ladderize %>% hang.dendrogram(hang = 0) %>% plot(horiz = TRUE)
725 ```
726
727
728
729
730
731 ### Adding extra bars and rectangles
732
733 #### Adding colored rectangles
734
735 Earlier we have seen how to highlight clusters in a dendrogram by coloring branches. We can also draw rectangles around the branches of a dendrogram in order to highlight the corresponding clusters. First the dendrogram is cut at a certain level, then a rectangle is drawn around selected branches. This is done using the `rect.dendrogram`, which is modeled based on the `rect.hclust` function. One advantage of `rect.dendrogram` over `rect.hclust`, is that it also works on horizontally plotted trees:
736
737
738
739 ```{r, fig.width=6, fig.height=3}
740 layout(t(c(1,1,1,2,2)))
741
742 dend15 %>% set("branches_k_color") %>% plot
743 dend15 %>% rect.dendrogram(k=3,
744 border = 8, lty = 5, lwd = 2)
745
746 dend15 %>% set("branches_k_color") %>% plot(horiz = TRUE)
747 dend15 %>% rect.dendrogram(k=3, horiz = TRUE,
748 border = 8, lty = 5, lwd = 2)
749
750 ```
751
752
753
754
755 #### Adding colored bars
756
757
758 Adding colored bars to a dendrogram may be useful to show clusters or some outside categorization of the items. For example:
759
760
761 ```{r, fig.width=4, fig.height=4}
762 is_odd <- ifelse(labels(dend15) %% 2, 2,3)
763 is_345 <- ifelse(labels(dend15) > 2, 3,4)
764 is_12 <- ifelse(labels(dend15) <= 2, 3,4)
765 k_3 <- cutree(dend15,k = 3, order_clusters_as_data = FALSE)
766 # The FALSE above makes sure we get the clusters in the order of the
767 # dendrogram, and not in that of the original data. It is like:
768 # cutree(dend15, k = 3)[order.dendrogram(dend15)]
769 the_bars <- cbind(is_odd, is_345, is_12, k_3)
770 the_bars[the_bars==2] <- 8
771
772 dend15 %>% plot
773 colored_bars(colors = the_bars, dend = dend15, sort_by_labels_order = FALSE)
774 # we use sort_by_labels_order = FALSE since "the_bars" were set based on the
775 # labels order. The more common use case is when the bars are based on a second variable
776 # from the same data.frame as dend was created from. Thus, the default
777 # sort_by_labels_order = TRUE would make more sense.
778 ```
779
780 Another example, based on mtcars (in which the default of `sort_by_labels_order = TRUE` makes sense):
781
782 ```{r}
783
784 dend_mtcars <- mtcars[, c("mpg", "disp")] %>% dist %>% hclust(method = "average") %>% as.dendrogram
785
786 par(mar = c(10,2,1,1))
787 plot(dend_mtcars)
788 the_bars <- ifelse(mtcars$am, "grey", "gold")
789 colored_bars(colors = the_bars, dend = dend_mtcars, rowLabels = "am")
790
791 ```
792
793
794
795
796 ggplot2 integration
797 --------------------------
798
799 The core process is to transform a dendrogram into a `ggdend` object using `as.ggdend`, and then plot it using `ggplot` (a new S3 `ggplot.ggdend` function is available). These two steps can be done in one command with either the function `ggplot` or `ggdend`.
800
801 The reason we want to have `as.ggdend` (and not only `ggplot.dendrogram`), is (1) so that you could create your own mapping of `ggdend` and, (2) since `as.ggdend` might be slow for large trees, it is probably better to be able to run it only once for such cases.
802
803 A `ggdend` class object is a list with 3 components: segments, labels, nodes. Each one contains the graphical parameters from the original dendrogram, but in a tabular form that can be used by `ggplot2+geom_segment+geom_text` to create a dendrogram plot.
804
805 The function `prepare.ggdend` is used by `plot.ggdend` to take the ggdend object and prepare it for plotting. This is because the defaults of various parameters in dendrogram's are not always stored in the object itself, but are built-in into the `plot.dendrogram` function. For example, the color of the labels is not (by default) specified in the dendrogram (only if we change it from black to something else). Hence, when taking the object into a different plotting engine (say ggplot2), we want to prepare the object by filling-in various defaults. This function is automatically invoked within the `plot.ggdend` function. You would probably use it only if you'd wish to build your own ggplot2 mapping.
806
807 ```{r}
808 # Create a complex dend:
809 dend <- iris[1:30,-5] %>% dist %>% hclust %>% as.dendrogram %>%
810 set("branches_k_color", k=3) %>% set("branches_lwd", c(1.5,1,1.5)) %>%
811 set("branches_lty", c(1,1,3,1,1,2)) %>%
812 set("labels_colors") %>% set("labels_cex", c(.9,1.2)) %>%
813 set("nodes_pch", 19) %>% set("nodes_col", c("orange", "black", "plum", NA))
814 # plot the dend in usual "base" plotting engine:
815 plot(dend)
816 # Now let's do it in ggplot2 :)
817 ggd1 <- as.ggdend(dend)
818 library(ggplot2)
819 # the nodes are not implemented yet.
820 ggplot(ggd1) # reproducing the above plot in ggplot2 :)
821 ggplot(ggd1, horiz = TRUE, theme = NULL) # horiz plot (and let's remove theme) in ggplot2
822 # Adding some extra spice to it...
823 # creating a radial plot:
824 # ggplot(ggd1) + scale_y_reverse(expand = c(0.2, 0)) + coord_polar(theta="x")
825 # The text doesn't look so great, so let's remove it:
826 ggplot(ggd1, labels = FALSE) + scale_y_reverse(expand = c(0.2, 0)) + coord_polar(theta="x")
827 ```
828
829
830 **Credit:** These functions are *extended* versions of the functions `ggdendrogram`, `dendro_data` (and the hidden `dendrogram_data`) from Andrie de Vries's [ggdendro](https://cran.r-project.org/package=ggdendro) package. The motivation for this fork is the need to add more graphical parameters to the plotted tree. This required a strong mixture of functions from ggdendro and dendextend (to the point that it seemed better to just fork the code into its current form).
831
832
833
834 Enhancing other packages
835 --------------------------
836
837 The dendextend package aims to extend and enhance features from the R ecosystem. Let us take a look at several examples.
838
839
840 ### DendSer
841
842 The DendSer package helps in re-arranging a dendrogram to optimize visualization-based cost functions. Until now it was only used for `hclust` objects, but it can easily be connected to `dendrogram` objects by trying to turn the dendrogram into hclust, on which it runs DendSer. This can be used to rotate the dendrogram easily by using the `rotate_DendSer` function:
843
844
845 ```{r, fig.width=7, fig.height=3}
846 if(require(DendSer)) {
847 par(mfrow = c(1,2))
848 DendSer.dendrogram(dend15)
849
850 dend15 %>% color_branches %>% plot
851 dend15 %>% color_branches %>% rotate_DendSer %>% plot
852 }
853 ```
854
855
856 ### gplots
857
858 The gplots package brings us the `heatmap.2` function. In it, we can use our modified dendrograms to get more informative heat-maps:
859
860 ```{r, message=FALSE, fig.width=7, fig.height=7}
861 library(gplots)
862
863 x <- as.matrix(datasets::mtcars)
864
865 heatmap.2(x)
866
867 # now let's spice up the dendrograms a bit:
868 Rowv <- x %>% dist %>% hclust %>% as.dendrogram %>%
869 set("branches_k_color", k = 3) %>% set("branches_lwd", 4) %>%
870 ladderize
871 # rotate_DendSer(ser_weight = dist(x))
872 Colv <- x %>% t %>% dist %>% hclust %>% as.dendrogram %>%
873 set("branches_k_color", k = 2) %>% set("branches_lwd", 4) %>%
874 ladderize
875 # rotate_DendSer(ser_weight = dist(t(x)))
876
877 heatmap.2(x, Rowv = Rowv, Colv = Colv)
878 ```
879
880
881 ### NMF
882
883 The same as gplots, NMF offers a heatmap function called `aheatmap`. We can update it just as we would `heatmap.2`.
884
885 Since NMF was removed from CRAN (it could still be installed from source), the example code is still available but not ran in this vignette.
886
887
888 ```{r, message=FALSE, eval = FALSE}
889
890 # library(NMF)
891 #
892 # x <- as.matrix(datasets::mtcars)
893 #
894 # # now let's spice up the dendrograms a bit:
895 # Rowv <- x %>% dist %>% hclust %>% as.dendrogram %>%
896 # set("branches_k_color", k = 3) %>% set("branches_lwd", 4) %>%
897 # ladderize
898 # # rotate_DendSer(ser_weight = dist(x))
899 # Colv <- x %>% t %>% dist %>% hclust %>% as.dendrogram %>%
900 # set("branches_k_color", k = 2) %>% set("branches_lwd", 4) %>%
901 # ladderize
902 # # rotate_DendSer(ser_weight = dist(t(x)))
903 #
904 # aheatmap(x, Rowv = Rowv, Colv = Colv)
905
906
907
908 ```
909
910
911
912 ### heatmaply
913
914 The heatmaply package create interactive heat-maps that are usable from the R console, in the 'RStudio' viewer pane, in 'R Markdown' documents, and in 'Shiny' apps. By hovering the mouse pointer over a cell or a dendrogram to show details, drag a rectangle to zoom.
915
916 The use is very similar to what we've seen before, we just use `heatmaply` instead of `heatmap.2`:
917
918
919 ```{r}
920 x <- as.matrix(datasets::mtcars)
921 # heatmaply(x)
922 # now let's spice up the dendrograms a bit:
923 Rowv <- x %>% dist %>% hclust %>% as.dendrogram %>%
924 set("branches_k_color", k = 3) %>% set("branches_lwd", 4) %>%
925 ladderize
926 # rotate_DendSer(ser_weight = dist(x))
927 Colv <- x %>% t %>% dist %>% hclust %>% as.dendrogram %>%
928 set("branches_k_color", k = 2) %>% set("branches_lwd", 4) %>%
929 ladderize
930 # rotate_DendSer(ser_weight = dist(t(x)))
931 ```
932
933 Here we need to use `cache=FALSe` in the markdown:
934
935 ```{r, message=FALSE, cache = FALSE, eval = FALSE}
936 library(heatmaply)
937 heatmaply(x, Rowv = Rowv, Colv = Colv)
938 ```
939
940 I avoided running the code from above due to space issues on CRAN. For live examples, please go to:
941
942 - https://talgalili.github.io/heatmaply/articles/heatmaply.html
943
944
945
946 ### dynamicTreeCut
947
948 The `cutreeDynamic` function offers a wrapper for two methods of adaptive branch pruning of hierarchical clustering dendrograms. The results of which can now be visualized by both updating the branches, as well as using the `colored_bars` function (which was adjusted for use with plots of dendrograms):
949
950
951 ```{r}
952 # let's get the clusters
953 library(dynamicTreeCut)
954 data(iris)
955 x <- iris[,-5] %>% as.matrix
956 hc <- x %>% dist %>% hclust
957 dend <- hc %>% as.dendrogram
958
959 # Find special clusters:
960 clusters <- cutreeDynamic(hc, distM = as.matrix(dist(x)), method = "tree")
961 # we need to sort them to the order of the dendrogram:
962 clusters <- clusters[order.dendrogram(dend)]
963 clusters_numbers <- unique(clusters) - (0 %in% clusters)
964 n_clusters <- length(clusters_numbers)
965
966 library(colorspace)
967 cols <- rainbow_hcl(n_clusters)
968 true_species_cols <- rainbow_hcl(3)[as.numeric(iris[,][order.dendrogram(dend),5])]
969 dend2 <- dend %>%
970 branches_attr_by_clusters(clusters, values = cols) %>%
971 color_labels(col = true_species_cols)
972 plot(dend2)
973 clusters <- factor(clusters)
974 levels(clusters)[-1] <- cols[-5][c(1,4,2,3)]
975 # Get the clusters to have proper colors.
976 # fix the order of the colors to match the branches.
977 colored_bars(clusters, dend, sort_by_labels_order = FALSE)
978 # here we used sort_by_labels_order = FALSE since the clusters were already sorted based on the dendrogram's order
979
980 ```
981
982
983 ### pvclust
984
985 The pvclust library calculates "p-values"" for hierarchical clustering via multiscale bootstrap re-sampling. Hierarchical clustering is done for given data and p-values are computed for each of the clusters. The dendextend package let's us reproduce the plot from pvclust, but with a dendrogram (instead of an hclust object), which also lets us extend the visualization.
986
987
988 ```{r, message=FALSE, fig.width=9, results='hide'}
989 par(mfrow = c(1,2))
990
991 library(pvclust)
992 data(lung) # 916 genes for 73 subjects
993 set.seed(13134)
994 result <- pvclust(lung[1:100, 1:10],
995 method.dist="cor", method.hclust="average", nboot=10)
996
997 # with pvrect
998 plot(result)
999 pvrect(result)
1000
1001 # with a dendrogram of pvrect
1002 dend <- as.dendrogram(result)
1003 result %>% as.dendrogram %>%
1004 plot(main = "Cluster dendrogram with AU/BP values (%)\n reproduced plot with dendrogram")
1005 result %>% text
1006 result %>% pvrect
1007 ```
1008
1009
1010 Let's color and thicken the branches based on the p-values:
1011
1012 ```{r, fig.height=8, fig.width=8}
1013 par(mfrow = c(2,2))
1014
1015 # with a modified dendrogram of pvrect
1016 dend %>% pvclust_show_signif(result) %>%
1017 plot(main = "Cluster dendrogram \n bp values are highlighted by signif")
1018
1019 dend %>% pvclust_show_signif(result, show_type = "lwd") %>%
1020 plot(main = "Cluster dendrogram with AU/BP values (%)\n bp values are highlighted by signif")
1021 result %>% text
1022 result %>% pvrect(alpha=0.95)
1023
1024
1025 dend %>% pvclust_show_signif_gradient(result) %>%
1026 plot(main = "Cluster dendrogram with AU/BP values (%)\n bp values are colored by signif")
1027
1028 dend %>%
1029 pvclust_show_signif_gradient(result) %>%
1030 pvclust_show_signif(result) %>%
1031 plot(main = "Cluster dendrogram with AU/BP values (%)\n bp values are colored+highlighted by signif")
1032 result %>% text
1033 result %>% pvrect(alpha=0.95)
1034 ```
1035
1036
1037
1038
1039 ### circlize
1040
1041 Circular layout is an efficient way for the visualization of huge amounts of information. The circlize package provides an implementation of circular layout generation in R, including a solution for dendrogram objects produced using dendextend:
1042
1043
1044 ```{r}
1045 library(circlize)
1046
1047 dend <- iris[1:40,-5] %>% dist %>% hclust %>% as.dendrogram %>%
1048 set("branches_k_color", k=3) %>% set("branches_lwd", c(5,2,1.5)) %>%
1049 set("branches_lty", c(1,1,3,1,1,2)) %>%
1050 set("labels_colors") %>% set("labels_cex", c(.6,1.5)) %>%
1051 set("nodes_pch", 19) %>% set("nodes_col", c("orange", "black", "plum", NA))
1052
1053 par(mar = rep(0,4))
1054 circlize_dendrogram(dend)
1055 # circlize_dendrogram(dend, labels = FALSE)
1056 # circlize_dendrogram(dend, facing = "inside", labels = FALSE)
1057 ```
1058
1059
1060 The above is a wrapper for functions in circlize. An advantage for using the circlize package directly is for plotting a circular dendrogram so that you can add more graphics for the elements in the tree just by adding more tracks using \link[circlize]{circos.track}. For example:
1061
1062
1063 ```{r}
1064 # dend <- iris[1:40,-5] %>% dist %>% hclust %>% as.dendrogram %>%
1065 # set("branches_k_color", k=3) %>% set("branches_lwd", c(5,2,1.5)) %>%
1066 # set("branches_lty", c(1,1,3,1,1,2)) %>%
1067 # set("labels_colors") %>% set("labels_cex", c(.9,1.2)) %>%
1068 # set("nodes_pch", 19) %>% set("nodes_col", c("orange", "black", "plum", NA))
1069
1070 set.seed(2015-07-10)
1071 # In the following we get the dendrogram but can also get extra information on top of it
1072 circos.initialize("foo", xlim = c(0, 40))
1073 circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
1074 circos.rect(1:40-0.8, rep(0, 40), 1:40-0.2, runif(40), col = rand_color(40), border = NA)
1075 }, bg.border = NA)
1076 circos.track(ylim = c(0, 1), panel.fun = function(x, y) {
1077 circos.text(1:40-0.5, rep(0, 40), labels(dend), col = labels_colors(dend),
1078 facing = "clockwise", niceFacing = TRUE, adj = c(0, 0.5))
1079 }, bg.border = NA, track.height = 0.1)
1080 max_height = attr(dend, "height")
1081 circos.track(ylim = c(0, max_height), panel.fun = function(x, y) {
1082 circos.dendrogram(dend, max_height = max_height)
1083 }, track.height = 0.5, bg.border = NA)
1084 circos.clear()
1085
1086
1087 ```
1088
1089
1090
1091
1092
1093
1094 Comparing two dendrograms
1095 --------------------------
1096
1097 ### dendlist
1098
1099 A `dendlist` is a function which produces the dendlist class. It accepts several dendrograms and/or dendlist objects and chain them all together. This function aim to help with the usability of comparing two or more dendrograms.
1100
1101 ```{r}
1102 dend15 <- c(1:5) %>% dist %>% hclust(method = "average") %>% as.dendrogram
1103 dend15 <- dend15 %>% set("labels_to_char")
1104 dend51 <- dend15 %>% set("labels", as.character(5:1)) %>% match_order_by_labels(dend15)
1105 dends_15_51 <- dendlist(dend15, dend51)
1106 dends_15_51
1107 head(dends_15_51)
1108 ```
1109
1110 The function `match_order_by_labels` makes sure that the order in the leaves corresponds to the same labels in both trees.
1111
1112 ### dend_diff
1113
1114 The `dend_diff` function plots two trees side by side, highlighting edges unique to each tree in red, it relies on the `distinct_edges` function.
1115
1116 For example:
1117
1118 ```{r}
1119 # example 1
1120 x <- 1:5 %>% dist %>% hclust %>% as.dendrogram
1121 y <- set(x, "labels", 5:1)
1122
1123 # example 2
1124 dend1 <- 1:10 %>% dist %>% hclust %>% as.dendrogram
1125 dend2 <- dend1 %>% set("labels", c(1,3,2,4, 5:10) )
1126 dend_diff(dend1, dend2)
1127 ```
1128
1129 See the `highlight_distinct_edges` function for more control over how to create the distinction (color, line width, line type).
1130
1131
1132 ### tanglegram
1133
1134 A tanglegram plot gives two dendrogram (with the same set of labels), one facing the other,
1135 and having their labels connected by lines. Tanglegram can be used for visually comparing
1136 two methods of Hierarchical clustering, and are sometimes used in biology when comparing
1137 two phylogenetic trees.
1138
1139 Here is an example of creating a tanglegram using dendextend:
1140
1141
1142 ```{r, fig.width=5, fig.height=3}
1143 tanglegram(dends_15_51)
1144 # Same as using:
1145 # plot(dends_15_51) # since there is a plot method for dendlist
1146 # and also:
1147 # tanglegram(dend15, dend51)
1148 ```
1149
1150 Notice how "unique" nodes are highlighted with dashed lines (i.e.: nodes which contains a combination of labels/items, which are not present in the other tree). This can be turned off using `highlight_distinct_edges = FALSE`.
1151 Also notice how the connecting lines are colored to highlight two sub-trees which are present in both dendrograms. This can be turned off by setting `common_subtrees_color_lines = FALSE`. We can also color the branches of the trees to show the two common sub-trees using `common_subtrees_color_branches = TRUE`:
1152
1153 ```{r, fig.width=5, fig.height=3}
1154 tanglegram(dends_15_51, common_subtrees_color_branches = TRUE)
1155 ```
1156
1157
1158
1159 We may wish to improve the layout of the trees. For this we have the `entanglement`, to measure the quality of the alignment of the two trees in the tanglegram layout, and the `untangle` function, for improving it.
1160
1161 ```{r}
1162 dends_15_51 %>% entanglement # lower is better
1163 # dends_15_51 %>% untangle(method = "DendSer") %>% entanglement # lower is better
1164 dends_15_51 %>% untangle(method = "step1side") %>% entanglement # lower is better
1165 ```
1166
1167 Notice that just because we can get two trees to have horizontal connecting lines, it doesn't mean these trees are identical (or even very similar topologically):
1168
1169 ```{r, fig.width=5, fig.height=3}
1170 dends_15_51 %>% untangle(method = "step1side") %>%
1171 tanglegram(common_subtrees_color_branches = TRUE)
1172 ```
1173
1174
1175
1176
1177 Entanglement is measured by giving the left tree's labels the values of 1 till tree size, and than match these numbers with the right tree. Now, entanglement is the L norm distance between these two vectors.
1178 That is, we take the sum of the absolute difference (each one in the power of L). e.g: `sum(abs(x-y)**L)`.
1179 And this is divided by the "worst case" entanglement level (e.g: when the right tree is the complete reverse of the left tree).
1180
1181 L tells us which penalty level we are at (L0, L1, L2, partial L's etc). L>1 means that we give a big penalty for sharp angles. While L->0 means that any time something is not a straight horizontal line, it gets a large penalty If L=0.1 it means that we much prefer straight lines over non straight lines
1182
1183 Finding an optimal rotation for the tanglegram of two dendrogram is a hard problem. This problem is also harder for larger trees.
1184
1185 Let's see how well some untangle methods can do.
1186
1187 Without doing anything:
1188
1189 ```{r, fig.width=5, fig.height=3}
1190 x <- dends_15_51
1191 x %>% plot(main = paste("entanglement =", round(entanglement(x), 2)))
1192 ```
1193
1194 Using DendSer:
1195
1196 ```{r, fig.width=5, fig.height=3}
1197 # x <- dends_15_51 %>% untangle(method = "DendSer")
1198 x <- dends_15_51 %>% untangle(method = "ladderize")
1199 x %>% plot(main = paste("entanglement =", round(entanglement(x), 2)))
1200 ```
1201
1202
1203 One solution for improving the tanglegram would be to randomly search the rotated tree space for a better solution. Here is how to use a random search:
1204
1205 ```{r, fig.width=5, fig.height=3}
1206 set.seed(3958)
1207 x <- dends_15_51 %>% untangle(method = "random", R = 10)
1208 x %>% plot(main = paste("entanglement =", round(entanglement(x), 2)))
1209 ```
1210
1211 We can see we already got something better. An advantage of the random search is the ability to create many many trees and compare them to find the best pair.
1212
1213 Let's use a greedy forward step wise rotation of the two trees (first the left, then the right, and so on), to see if we can find a better solution for comparing the two trees. Notice that this may take some time to run (the larger the tree, the longer it would take), but we can limit the search for smaller k's, and see what improvement that can bring us using step2side (slowest):
1214
1215 ```{r, fig.width=5, fig.height=3}
1216 x <- dends_15_51 %>% untangle(method = "step2side")
1217 x %>% plot(main = paste("entanglement =", round(entanglement(x), 2)))
1218 ```
1219
1220 We got perfect entanglement (0).
1221
1222
1223
1224 ### Correlation measures
1225
1226 We shall use the following for the upcoming examples:
1227
1228 ```{r}
1229 set.seed(23235)
1230 ss <- sample(1:150, 10 )
1231 dend1 <- iris[ss,-5] %>% dist %>% hclust("com") %>% as.dendrogram
1232 dend2 <- iris[ss,-5] %>% dist %>% hclust("single") %>% as.dendrogram
1233 dend3 <- iris[ss,-5] %>% dist %>% hclust("ave") %>% as.dendrogram
1234 dend4 <- iris[ss,-5] %>% dist %>% hclust("centroid") %>% as.dendrogram
1235
1236 dend1234 <- dendlist("Complete" = dend1, "Single" = dend2, "Average" = dend3, "Centroid" = dend4)
1237
1238 par(mfrow = c(2,2))
1239 plot(dend1, main = "Complete")
1240 plot(dend2, main = "Single")
1241 plot(dend3, main = "Average")
1242 plot(dend4, main = "Centroid")
1243
1244 ```
1245
1246
1247 #### Global Comparison of two (or more) dendrograms
1248
1249 The `all.equal.dendrogram` function makes a global comparison of two or more dendrograms trees.
1250
1251 ```{r}
1252 all.equal(dend1, dend1)
1253 all.equal(dend1, dend2)
1254 all.equal(dend1, dend2, use.edge.length = FALSE)
1255 all.equal(dend1, dend2, use.edge.length = FALSE, use.topology = FALSE)
1256
1257 all.equal(dend2, dend4, use.edge.length = TRUE)
1258 all.equal(dend2, dend4, use.edge.length = FALSE)
1259
1260 all.equal(dendlist(dend1, dend1, dend1))
1261
1262 all.equal(dend1234)
1263 all.equal(dend1234, use.edge.length = FALSE)
1264 ```
1265
1266
1267
1268 #### Distance matrix using dist.dendlist
1269
1270 The `dist.dendlist` function computes the Robinson-Foulds distance (also known as symmetric difference) between two dendrograms. This is the sum of edges in both trees with labels that exist in only one of the two trees (i.e.: the length of `distinct_edges`).
1271
1272 ```{r}
1273 x <- 1:5 %>% dist %>% hclust %>% as.dendrogram
1274 y <- set(x, "labels", 5:1)
1275
1276 dist.dendlist(dendlist(x1 = x,x2 = x,y1 = y))
1277 dend_diff(x,y)
1278
1279 dist.dendlist(dend1234)
1280 ```
1281
1282
1283
1284 This function might implement other topological distances in the future.
1285
1286
1287
1288 #### Correlation matrix using cor.dendlist
1289
1290 Both Baker's Gamma and cophenetic correlation (Which will be introduced shortly), can be calculated to create a correlation matrix using the `cor.dendlist` function (the default method is cophenetic correlation):
1291
1292
1293 ```{r}
1294 cor.dendlist(dend1234)
1295 ```
1296
1297 The corrplot library offers a nice visualization:
1298
1299 ```{r}
1300 library(corrplot)
1301 corrplot(cor.dendlist(dend1234), "pie", "lower")
1302 ```
1303
1304 Which easily tells us that single, average and centroid give similar results, while complete is somewhat different.
1305
1306
1307 ```{r, fig.width=5, fig.height=3}
1308 # same subtrees, so there is no need to color the branches
1309 dend1234 %>% tanglegram(which = c(2,3))
1310 # Here the branches colors are very helpful:
1311 dend1234 %>% tanglegram(which = c(1,2),
1312 common_subtrees_color_branches = TRUE)
1313
1314 ```
1315
1316
1317
1318 #### Baker's Gamma Index
1319
1320 Baker's Gamma Index (see baker's paper from 1974) is a measure of association (similarity)
1321 between two trees of Hierarchical clustering (dendrograms). It is defined as the rank correlation between the stages at which pairs of objects combine in each of the two trees.
1322
1323 Or more detailed: It is calculated by taking two items, and see what is the highest
1324 possible level of k (number of cluster groups created when cutting the tree)
1325 for which the two item still belongs to the same tree. That k is returned,
1326 and the same is done for these two items for the second tree.
1327 There are n over 2 combinations of such pairs of items from the items in
1328 the tree, and all of these numbers are calculated for each of the two trees.
1329 Then, these two sets of numbers (a set for the items in each tree)
1330 are paired according to the pairs of items compared, and a Spearman
1331 correlation is calculated.
1332
1333 The value can range between -1 to 1. With near 0 values meaning that
1334 the two trees are not statistically similar.
1335 For exact p-value one should use a permutation test. One such option
1336 will be to permute over the labels of one tree many times, calculating
1337 the distribution under the null hypothesis (keeping the trees topologies
1338 constant).
1339
1340 Notice that this measure is not affected by the height of a branch but only
1341 of its relative position compared with other branches.
1342
1343
1344 ```{r}
1345 cor_bakers_gamma(dend15, dend51)
1346 ```
1347
1348 Even that we can reach perfect entanglement, Baker's gamma shows us that the tree's topology is not identical. As opposed with the correlation of a tree with itself:
1349
1350 ```{r}
1351 cor_bakers_gamma(dend15, dend15)
1352 ```
1353
1354 Since the observations creating the Baker's Gamma Index of such a measure are correlated, we need to perform a permutation test for the calculation of the statistical significance of the index. Let's look at the distribution of Baker's Gamma Index under the null hypothesis (assuming fixed tree topologies). This will be different for different tree structures and sizes. Here are the results when the compared tree is itself (after shuffling its own labels), and when comparing tree 1 to the shuffled tree 2:
1355
1356
1357 ```{r}
1358 set.seed(23235)
1359 the_cor <- cor_bakers_gamma(dend15, dend15)
1360 the_cor2 <- cor_bakers_gamma(dend15, dend51)
1361 the_cor
1362 the_cor2
1363
1364 R <- 100
1365 cor_bakers_gamma_results <- numeric(R)
1366 dend_mixed <- dend15
1367 for(i in 1:R) {
1368 dend_mixed <- sample.dendrogram(dend_mixed, replace = FALSE)
1369 cor_bakers_gamma_results[i] <- cor_bakers_gamma(dend15, dend_mixed)
1370 }
1371 plot(density(cor_bakers_gamma_results),
1372 main = "Baker's gamma distribution under H0",
1373 xlim = c(-1,1))
1374 abline(v = 0, lty = 2)
1375 abline(v = the_cor, lty = 2, col = 2)
1376 abline(v = the_cor2, lty = 2, col = 4)
1377 legend("topleft", legend = c("cor", "cor2"), fill = c(2,4))
1378 round(sum(the_cor2 < cor_bakers_gamma_results)/ R, 4)
1379 title(sub = paste("One sided p-value:",
1380 "cor =", round(sum(the_cor < cor_bakers_gamma_results)/ R, 4),
1381 " ; cor2 =", round(sum(the_cor2 < cor_bakers_gamma_results)/ R, 4)
1382 ))
1383 ```
1384
1385 We can see that we do not have enough evidence that dend15 and dend51 are significantly "similar" (i.e.: with a correlation larger than 0).
1386
1387 We can also build a bootstrap confidence interval, using `sample.dendrogram`, for the correlation. This function can be very slow for larger trees, so make sure you use if carefully:
1388
1389 ```{r, warning=FALSE}
1390
1391 dend1 <- dend15
1392 dend2 <- dend51
1393
1394 set.seed(23801)
1395
1396 R <- 100
1397 dend1_labels <- labels(dend1)
1398 dend2_labels <- labels(dend2)
1399 cor_bakers_gamma_results <- numeric(R)
1400 for(i in 1:R) {
1401 sampled_labels <- sample(dend1_labels, replace = TRUE)
1402 # members needs to be fixed since it will be later used in nleaves
1403 dend_mixed1 <- sample.dendrogram(dend1,
1404 dend_labels=dend1_labels,
1405 fix_members=TRUE,fix_order=TRUE,fix_midpoint=FALSE,
1406 replace = TRUE, sampled_labels=sampled_labels
1407 )
1408 dend_mixed2 <- sample.dendrogram(dend2, dend_labels=dend2_labels,
1409 fix_members=TRUE,fix_order=TRUE,fix_midpoint=FALSE,
1410 replace = TRUE, sampled_labels=sampled_labels
1411 )
1412 cor_bakers_gamma_results[i] <- cor_bakers_gamma(dend_mixed1, dend_mixed2, warn = FALSE)
1413 }
1414
1415
1416 # here is the tanglegram
1417 tanglegram(dend1, dend2)
1418 # And here is the tanglegram for one sample of our trees:
1419 dend_mixed1 <- rank_order.dendrogram(dend_mixed1)
1420 dend_mixed2 <- rank_order.dendrogram(dend_mixed2)
1421 dend_mixed1 <- fix_members_attr.dendrogram(dend_mixed1)
1422 dend_mixed2 <- fix_members_attr.dendrogram(dend_mixed2)
1423 tanglegram(dend_mixed1, dend_mixed2)
1424 cor_bakers_gamma(dend_mixed1, dend_mixed2, warn = FALSE)
1425
1426
1427 CI95 <- quantile(cor_bakers_gamma_results, probs=c(.025,.975))
1428 CI95
1429 par(mfrow = c(1,1))
1430 plot(density(cor_bakers_gamma_results),
1431 main = "Baker's gamma bootstrap distribution",
1432 xlim = c(-1,1))
1433 abline(v = CI95, lty = 2, col = 3)
1434 abline(v = cor_bakers_gamma(dend1, dend2), lty = 2, col = 2)
1435 legend("topleft", legend =c("95% CI", "Baker's Gamma Index"), fill = c(3,2))
1436
1437
1438 ```
1439
1440 The bootstrap sampling can do weird things with small trees. In this case we had many times that the two trees got perfect correlation. The usage and interpretation should be done carefully!
1441
1442 #### Cophenetic correlation
1443
1444 The cophenetic distance between two observations that have been clustered is defined to be the inter-group dissimilarity at which the two observations are first combined into a single cluster. This distance has many ties and restrictions. The cophenetic correlation (see sokal 1962) is the correlation between two cophenetic distance matrices of two trees.
1445
1446 The value can range between -1 to 1. With near 0 values meaning that the two trees are not statistically similar. For exact p-value one should result to a permutation test. One such option will be to permute over the labels of one tree many times, and calculating the distribution under the null hypothesis (keeping the trees topologies constant).
1447
1448
1449 ```{r}
1450 cor_cophenetic(dend15, dend51)
1451 ```
1452
1453 The function `cor_cophenetic` is faster than `cor_bakers_gamma`, and might be preferred for that reason.
1454
1455
1456 ### The Fowlkes-Mallows Index and the Bk plot
1457
1458 #### The Fowlkes-Mallows Index
1459
1460 The Fowlkes-Mallows Index (see fowlkes 1983) (FM Index, or Bk) is a measure of similarity between two clusterings. The FM index ranges from 0 to 1, a higher value indicates a greater similarity between the two clusters.
1461
1462 The dendextend package allows the calculation of FM-Index, its expectancy and variance under the null hypothesis, and a creation of permutations of the FM-Index under H0. Thanks to the profdpm package, we have another example of calculating the FM (though it does not offer the expectancy and variance under H0):
1463
1464
1465 ```{r}
1466 hc1 <- hclust(dist(iris[,-5]), "com")
1467 hc2 <- hclust(dist(iris[,-5]), "single")
1468
1469 # FM index of a cluster with himself is 1:
1470 FM_index(cutree(hc1, k=3), cutree(hc1, k=3))
1471 # FM index of two clusterings:
1472 FM_index(cutree(hc1, k=3), cutree(hc2, k=3))
1473 # we got a value far above the expected under H0
1474
1475 # Using the R code:
1476 FM_index_R(cutree(hc1, k=3), cutree(hc2, k=3))
1477 ```
1478
1479 The E_FM and V_FM are the values expected under the null hypothesis that the two trees have the same topology but one is a random shuffle of the labels of the other (i.e.: "no connection" between the trees).
1480
1481 So for the values:
1482 ```{r}
1483 FM_index(cutree(hc1, k=3), cutree(hc2, k=3))
1484 ```
1485
1486 We can take (under a normal asymptotic distribution)
1487 ```{r}
1488 0.4462 + 1.645 * sqrt(6.464092e-05)
1489 ```
1490
1491
1492 And since 0.8059 (our value) > 0.4594 (the critical value under H0, with alpha=5% for a one sided test) - then we can say that we significantly reject the hypothesis that the two trees are "not-similar".
1493
1494
1495 #### The Bk plot
1496
1497 In the Bk method we calculate the FM Index (Bk) for each k (k=2,3,...,n-1) number of clusters, giving the association between the two trees when each is cut to have k groups. The similarity between two hierarchical clustering dendrograms, can be investigated, using the (k,Bk) plot: For every level of splitting of the two dendrograms which produces k clusters in each tree, the plot shows the number Bk, and therefore enables the investigation of potential nuances in the structure of similarity. The Bk measures the number of pairs of items which are in the same cluster in both dendrograms, one of the clusters in one of the trees and one of the clusters in the other tree, divided by the geometric mean of the number of pairs of items which are in the same cluster in each tree. Namely, ${a_{uv}} = 1\left( {or{\rm{ }}{{\rm{b}}_{uv}} = 1} \right)$ if the items u and v are in the same cluster in the first tree (second tree), when it is cut so to give k clusters, and otherwise 0:
1498
1499 \[{FM_k} = {B_k} = \frac{{\sum\limits_{}^{} {{a_{uv}}{b_{uv}}} }}{{\sqrt {\sum\limits_{}^{} {{a_{uv}}} \sum\limits_{}^{} {{b_{uv}}} } }}\]
1500
1501 The Bk measure can be plotted for every value of k (except k=n) in order to create the "(k,Bk) plot". The plot compares the similarity of the two trees for different cuts. The mean and variance of Bk, under the null hypothesis (that the two trees are not "similar"), and under the assumption that the margins of the matching matrix are fixed, are given in Fowlkes and Mallows (see fowlkes 1983). They allow making inference on whether the results obtained are different from what would have been expected under the null hypothesis (of now particular order of the trees' labels).
1502
1503 The `Bk` and the `Bk_plot` functions allow the calculation of the FM-Index for a range of k values on two trees. Here are examples:
1504
1505
1506 ```{r}
1507 set.seed(23235)
1508 ss <- TRUE # sample(1:150, 30 ) # TRUE #
1509 hc1 <- hclust(dist(iris[ss,-5]), "com")
1510 hc2 <- hclust(dist(iris[ss,-5]), "single")
1511 dend1 <- as.dendrogram(hc1)
1512 dend2 <- as.dendrogram(hc2)
1513 # cutree(tree1)
1514
1515 # It works the same for hclust and dendrograms:
1516 Bk(hc1, hc2, k = 3)
1517 Bk(dend1, dend2, k = 3)
1518 ```
1519
1520
1521 The Bk plot:
1522
1523 ```{r, warning=FALSE}
1524 Bk_plot(hc1, hc2, main = "WRONG Bk plot \n(due to the way cutree works with ties in hclust)", warn = FALSE)
1525 Bk_plot(dend1, dend2, main = "CORRECT Bk plot \n(based on dendrograms)")
1526 ```
1527
1528
1529
1530
1531 Session info
1532 =============
1533
1534 ```{r, cache=FALSE}
1535 sessionInfo()
1536 ```