Introduction to dendextend

Tal Galili

2020-08-25

Author: Tal Galili ( Tal.Galili@gmail.com )

tl;dr: the dendextend package let’s you create figures like this:

Introduction

The dendextend package offers a set of functions for extending dendrogram objects in R, letting you visualize and compare trees of hierarchical clusterings, you can:

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).

Prerequisites

Acknowledgement

This package was made possible by the the support of my thesis adviser Yoav Benjamini, as well as code contributions from many R users. They are:

#>  [1] "Tal Galili <tal.galili@gmail.com> [aut, cre, cph] (https://www.r-statistics.com)"                 
#>  [2] "Gavin Simpson [ctb]"                                                                              
#>  [3] "Gregory Jefferis <jefferis@gmail.com> [ctb] (imported code from his dendroextras package)"        
#>  [4] "Marco Gallotta [ctb] (a.k.a: marcog)"                                                             
#>  [5] "Johan Renaudie [ctb] (https://github.com/plannapus)"                                              
#>  [6] "R core team [ctb] (Thanks for the Infastructure, and code in the examples)"                       
#>  [7] "Kurt Hornik [ctb]"                                                                                
#>  [8] "Uwe Ligges [ctb]"                                                                                 
#>  [9] "Andrej-Nikolai Spiess [ctb]"                                                                      
#> [10] "Steve Horvath <SHorvath@mednet.ucla.edu> [ctb]"                                                   
#> [11] "Peter Langfelder <Peter.Langfelder@gmail.com> [ctb]"                                              
#> [12] "skullkey [ctb]"                                                                                   
#> [13] "Mark Van Der Loo <mark.vanderloo@gmail.com> [ctb] (https://github.com/markvanderloo d3dendrogram)"
#> [14] "Yoav Benjamini [ths]"

The design of the dendextend package (and this manual!) is heavily inspired by Hadley Wickham’s work. Especially his text on writing an R package, the devtools package, and the dplyr package (specifically the use of chaining, and the Introduction text to dplyr).

Chaining

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.

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:

Or, you can also wrap the function calls inside each other:

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).

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.

For example, the following will be written as it would be explained:

For more details, you may look at:

A dendrogram is a nested list of lists with attributes

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:

And here is its structure (a nested list of lists with attributes):

#> List of 2
#>  $ : int 1
#>   ..- attr(*, "label")= int 1
#>   ..- attr(*, "members")= int 1
#>   ..- attr(*, "height")= num 0
#>   ..- attr(*, "leaf")= logi TRUE
#>  $ : int 2
#>   ..- attr(*, "label")= int 2
#>   ..- attr(*, "members")= int 1
#>   ..- attr(*, "height")= num 0
#>   ..- attr(*, "leaf")= logi TRUE
#>  - attr(*, "members")= int 2
#>  - attr(*, "midpoint")= num 0.5
#>  - attr(*, "height")= num 1
#> [1] "dendrogram"

Installation

To install the stable version on CRAN use:

To install the GitHub version:

And then you may load the package using:

How to explore a dendrogram’s parameters

Taking a first look at a dendrogram

For the following simple tree:

Here are some basic parameters we can get:

#> [1] 1 2 5 3 4
#> [1] 5
#> [1] 9
#> --[dendrogram w/ 2 branches and 5 members at h = 4]
#>   |--[dendrogram w/ 2 branches and 2 members at h = 1]
#>   |  |--leaf 1 
#>   |  `--leaf 2 
#>   `--[dendrogram w/ 2 branches and 3 members at h = 2]
#>      |--leaf 5 
#>      `--[dendrogram w/ 2 branches and 2 members at h = 1]
#>         |--leaf 3 
#>         `--leaf 4 
#> etc...

Next let us look at more sophisticated outputs.

How to change a dendrogram

The “set” function

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:

  1. object: a dendrogram object,
  2. what: a character indicating what is the property of the tree that should be set/updated
  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.

The what parameter accepts many options, each uses some general function in the background. These options deal with labels, nodes and branches. They are:

Two simple trees to play with

For illustration purposes, we will create several small tree, and demonstrate these functions on them.

Setting a dendrogram’s labels

We can get a vector with the tree’s labels:

#> [1] 1 2 5 3 4

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:

#> [1] 111 112 113 114 115

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.

#> [1] 1 2 5 3 4
#> [1] "1" "2" "5" "3" "4"

We may also change their color and size:

The function recycles, from left to right, the vector of values we give it. We can use this to create more complex patterns:

Notice how these “labels parameters” are nested within the nodePar attribute:

#>  int 1
#>  - attr(*, "label")= int 111
#>  - attr(*, "members")= int 1
#>  - attr(*, "height")= num 0
#>  - attr(*, "leaf")= logi TRUE
#>  - attr(*, "nodePar")=List of 3
#>   ..$ lab.col: num 1
#>   ..$ pch    : logi NA
#>   ..$ lab.cex: num 2
#>         [,1]
#> lab.col 1   
#> pch     NA  
#> lab.cex 2

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):

Setting a dendrogram’s nodes/leaves (points)

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 example:

And with recycling we can produce more complex outputs:

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:

#>     [,1] [,2] [,3] [,4] [,5] [,6] [,7] [,8] [,9]
#> pch 19   1    4    19   1    4    19   1    4   
#> cex 2    1    2    2    1    2    2    1    2   
#> col 3    4    3    4    3    4    3    4    3

We can also change the height of of the leaves by using the hang.dendrogram function:

An example of what this function does to the leaves heights:

#> [1] 0 0 0
#> [1] 1.35 0.85 0.85

We can also control the general heights of nodes using raise.dendrogram:

If you wish to make the branches under the root have the same height, you can use the flatten.dendrogram function.

Setting a dendrogram’s branches

Adjusting all branches

Similar to adjusting nodes, we can also control line width (lwd), line type (lty), and color (col) for branches:

We may also use recycling to create more complex patterns:

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).

Highlighting branches’ different heights using line width and color

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:

Tanglegrams are even easier to compare when using

Changing a dendrogram’s structure

Rotation

A dendrogram is an object which can be rotated on its hinges without changing its topology. Rotating a dendrogram in base R can be done using the reorder function. The problem with this function is that it is not very intuitive. For this reason the rotate function was written. 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 character vector. Or, the order parameter can also be a character vector of the labels of the tree, given in the new desired order of the tree. 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.

A new convenience S3 function for sort (sort.dendrogram) was added:

Adding extra bars and rectangles

Adding colored rectangles

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:

ggplot2 integration

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.

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.

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.

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.

# Create a complex dend:
dend <- iris[1:30,-5] %>% dist %>% hclust %>% as.dendrogram %>%
   set("branches_k_color", k=3) %>% set("branches_lwd", c(1.5,1,1.5)) %>%
   set("branches_lty", c(1,1,3,1,1,2)) %>%
   set("labels_colors") %>% set("labels_cex", c(.9,1.2)) %>% 
   set("nodes_pch", 19) %>% set("nodes_col", c("orange", "black", "plum", NA))
# plot the dend in usual "base" plotting engine:
plot(dend)

# Now let's do it in ggplot2 :)
ggd1 <- as.ggdend(dend)
library(ggplot2)
# the nodes are not implemented yet.
ggplot(ggd1) # reproducing the above plot in ggplot2 :)

ggplot(ggd1, horiz = TRUE, theme = NULL) # horiz plot (and let's remove theme) in ggplot2

# Adding some extra spice to it...
# creating a radial plot:
# ggplot(ggd1) + scale_y_reverse(expand = c(0.2, 0)) + coord_polar(theta="x")
# The text doesn't look so great, so let's remove it:
ggplot(ggd1, labels = FALSE) + scale_y_reverse(expand = c(0.2, 0)) + coord_polar(theta="x")

Credit: These functions are extended versions of the functions ggdendrogram, dendro_data (and the hidden dendrogram_data) from Andrie de Vries’s 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).

Enhancing other packages

The dendextend package aims to extend and enhance features from the R ecosystem. Let us take a look at several examples.

DendSer

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:

gplots

The gplots package brings us the heatmap.2 function. In it, we can use our modified dendrograms to get more informative heat-maps:

NMF

The same as gplots, NMF offers a heatmap function called aheatmap. We can update it just as we would heatmap.2.

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.

heatmaply

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.

The use is very similar to what we’ve seen before, we just use heatmaply instead of heatmap.2:

Here we need to use cache=FALSe in the markdown:

I avoided running the code from above due to space issues on CRAN. For live examples, please go to:

dynamicTreeCut

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):

pvclust

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.

Let’s color and thicken the branches based on the p-values:

circlize

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: