| 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 |
#' @title Draw Rectangles Around a Dendrogram's Clusters |
| 21 |
#' @export |
| 22 |
#' @description |
| 23 |
#' Draws rectangles around the branches of a dendrogram |
| 24 |
#' highlighting the corresponding clusters. |
| 25 |
#' First the dendrogram is cut at a certain level, |
| 26 |
#' then a rectangle is drawn around selected branches. |
| 27 |
#' @param tree a \link{dendrogram} object. |
| 28 |
#' @param k Scalar. Cut the dendrogram such that exactly k clusters (if possible) are produced. |
| 29 |
#' @param h Scalar. Cut the dendrogram by cutting at height h. (k overrides h) |
| 30 |
#' @param which A vector selecting the clusters around |
| 31 |
#' which a rectangle should be drawn. which selects clusters by number |
| 32 |
#' (from left to right in the tree), Default is which = 1:k. |
| 33 |
#' @param x A vector selecting the clusters around |
| 34 |
#' which a rectangle should be drawn. x selects clusters |
| 35 |
#' containing the respective horizontal coordinates. |
| 36 |
#' @param border Vector with border colors for the rectangles. |
| 37 |
#' @param cluster Optional vector with cluster memberships as returned by |
| 38 |
#' cutree(dend_obj, k = k), can be specified for efficiency if already computed. |
| 39 |
#' @param horiz logical (FALSE), indicating if the rectangles |
| 40 |
#' should be drawn horizontally or not (for when using |
| 41 |
#' plot(dend, horiz = TRUE) ) . |
| 42 |
#' @param density Passed to \link{rect}: the density of shading lines, |
| 43 |
#' in lines per inch. The default value of NULL means that |
| 44 |
#' no shading lines are drawn. A zero value of density means |
| 45 |
#' no shading lines whereas negative values (and NA) |
| 46 |
#' suppress shading (and so allow color filling). |
| 47 |
#' If border is a vector of colors, the color of density will default to 1. |
| 48 |
#' @param angle Passed to \link{rect}: angle (in degrees) of the shading lines. |
| 49 |
#' (default is 45) |
| 50 |
#' @param text a character vector of labels to plot underneath the clusters. |
| 51 |
#' When NULL (default), no text is displayed. |
| 52 |
#' @param text_cex a numeric (scalar) value of the text's cex value. |
| 53 |
#' @param text_col a (scalar) value of the text's col(or) value. |
| 54 |
#' @param xpd A logical value (or NA.), passed to \link{par}. |
| 55 |
#' Default is TRUE, in order to allow the rect to be below the labels. |
| 56 |
#' If FALSE, all plotting is clipped to the plot region, if TRUE, |
| 57 |
#' all plotting is clipped to the figure region, and if NA, all plotting |
| 58 |
#' is clipped to the device region. See also \link{clip}. |
| 59 |
#' @param lower_rect a (scalar) value of how low should the lower part of the rect be. |
| 60 |
#' If missing, it will take the value of par("usr")[3L] (or par("usr")[2L], depending |
| 61 |
#' if horiz = TRUE or not), with also the width of the labels. (notice that we |
| 62 |
#' would like to keep xpd = TRUE if we want the rect to be after the labels!) |
| 63 |
#' You can use a value such as 0, to get the rect above the labels. |
| 64 |
#' |
| 65 |
#' Notice that for a plot with small margins, it would be better to set this |
| 66 |
#' parameter manually. |
| 67 |
#' @param upper_rect a (scalar) value to add (default is 0) to how high should the upper part of the rect be. |
| 68 |
#' @param prop_k_height a (scalar) value (should be between 0 to 1), indicating what proportion |
| 69 |
#' of the height our rect will be between the height needed for k and k+1 clustering. |
| 70 |
#' @param stop_if_out logical (default is TRUE). This makes the function |
| 71 |
#' stop if k of the locator is outside the range (this default reproduces the behavior |
| 72 |
#' of the rect.hclust function). |
| 73 |
#' @param ... parameters passed to rect (such as lwd, lty, etc.) |
| 74 |
#' @seealso |
| 75 |
#' \link{rect.hclust}, \link{order.dendrogram}, \link{cutree.dendrogram} |
| 76 |
#' @return |
| 77 |
#' (Invisibly) returns a list where each element contains a vector |
| 78 |
#' of data points contained in the respective cluster. |
| 79 |
#' @source |
| 80 |
#' This function is based on \link{rect.hclust}, with slight modifications |
| 81 |
#' to have it work with a dendrogram, as well as a few added features |
| 82 |
#' (e.g: ... to rect, and horiz) |
| 83 |
#' |
| 84 |
#' The idea of adding text and shading lines under the clusters comes from |
| 85 |
#' skullkey from here: |
| 86 |
#' \url{https://stackoverflow.com/questions/4720307/change-dendrogram-leaves} |
| 87 |
#' |
| 88 |
#' @examples |
| 89 |
#' |
| 90 |
#' set.seed(23235) |
| 91 |
#' ss <- sample(1:150, 10) |
| 92 |
#' hc <- iris[ss, -5] %>% |
| 93 |
#' dist() %>% |
| 94 |
#' hclust() |
| 95 |
#' dend <- hc %>% as.dendrogram() |
| 96 |
#' |
| 97 |
#' plot(dend) |
| 98 |
#' rect.dendrogram(dend, 2, border = 2) |
| 99 |
#' rect.dendrogram(dend, 3, border = 4) |
| 100 |
#' Vectorize(rect.dendrogram, "k")(dend, 4:5, border = 6) |
| 101 |
#' |
| 102 |
#' plot(dend) |
| 103 |
#' rect.dendrogram(dend, 3, |
| 104 |
#' border = 1:3, |
| 105 |
#' density = 2, text = c("1", "b", "miao"), text_cex = 3 |
| 106 |
#' ) |
| 107 |
#' |
| 108 |
#' plot(dend) |
| 109 |
#' rect.dendrogram(dend, 4, which = c(1, 3), border = c(2, 3)) |
| 110 |
#' rect.dendrogram(dend, 4, x = 5, border = c(4)) |
| 111 |
#' rect.dendrogram(dend, 3, border = 3, lwd = 2, lty = 2) |
| 112 |
#' # now THIS, you can not do with the old rect.hclust |
| 113 |
#' plot(dend, horiz = TRUE) |
| 114 |
#' rect.dendrogram(dend, 2, border = 2, horiz = TRUE) |
| 115 |
#' rect.dendrogram(dend, 4, border = 4, lty = 2, lwd = 3, horiz = TRUE) |
| 116 |
#' |
| 117 |
#' # This had previously failed since it worked with a wrong k. |
| 118 |
#' |
| 119 |
#' dend15 <- c(1:5) %>% |
| 120 |
#' dist() %>% |
| 121 |
#' hclust(method = "average") %>% |
| 122 |
#' as.dendrogram() |
| 123 |
#' # dend15 <- c(1:25) %>% dist %>% hclust(method = "average") %>% as.dendrogram |
| 124 |
#' dend15 %>% |
| 125 |
#' set("branches_k_color") %>% |
| 126 |
#' plot() |
| 127 |
#' dend15 %>% rect.dendrogram( |
| 128 |
#' k = 3, |
| 129 |
#' border = 8, lty = 5, lwd = 2 |
| 130 |
#' ) |
| 131 |
rect.dendrogram <- function(tree, k = NULL, which = NULL, x = NULL, h = NULL, border = 2, |
| 132 |
cluster = NULL, horiz = FALSE, density = NULL, angle = 45, |
| 133 |
text = NULL, text_cex = 1, text_col = 1, xpd = TRUE, |
| 134 |
lower_rect, upper_rect = 0, prop_k_height = 0.5, |
| 135 |
stop_if_out = FALSE, |
| 136 |
...) { |
| 137 |
if (!is.dendrogram(tree)) stop("x is not a dendrogram object.") |
| 138 |
|
| 139 |
if (length(h) > 1L | length(k) > 1L) { |
| 140 |
stop("'k' and 'h' must be a scalar(i.e.: of length 1)") |
| 141 |
} |
| 142 |
|
| 143 |
# In tree_heights I am removing the first element |
| 144 |
# in order to be consistant with rect.hclust |
| 145 |
tree_heights <- heights_per_k.dendrogram(tree)[-1] # this is NOT really tree heights, but the height for which you need to cut in order to cut the tree |
| 146 |
tree_order <- order.dendrogram(tree) |
| 147 |
# rm0 <- function(x) x[x != 0] |
| 148 |
# height_to_add <- min(rm0(abs(diff(tree_heights))))/2 # the height to add so to be sure we get a "clear" cut |
| 149 |
|
| 150 |
|
| 151 |
|
| 152 |
if (!is.null(h)) { |
| 153 |
if (!is.null(k)) { |
| 154 |
stop("specify exactly one of 'k' and 'h'") |
| 155 |
} |
| 156 |
|
| 157 |
ss_ks <- tree_heights > h |
| 158 |
k <- max(as.numeric(names(ss_ks))[ss_ks]) |
| 159 |
k <- max(k, 2) # I don't like this default... |
| 160 |
} |
| 161 |
else if (is.null(k)) { |
| 162 |
stop("specify exactly one of 'k' and 'h'") |
| 163 |
} |
| 164 |
if (k < 2 | k > length(tree_heights)) { |
| 165 |
if (stop_if_out) { |
| 166 |
stop(gettextf("k must be between 2 and %d", length(tree_heights)), |
| 167 |
domain = NA |
| 168 |
) |
| 169 |
} else { |
| 170 |
warning(gettextf("k must be between 2 and %d", length(tree_heights)), |
| 171 |
domain = NA |
| 172 |
) |
| 173 |
} |
| 174 |
} |
| 175 |
if (is.null(cluster)) { |
| 176 |
cluster <- cutree(tree, k = k) |
| 177 |
} |
| 178 |
|
| 179 |
clustab <- table(cluster)[unique(cluster[tree_order])] |
| 180 |
|
| 181 |
m <- c(0, cumsum(clustab)) |
| 182 |
if (!is.null(x)) { |
| 183 |
if (!is.null(which)) { |
| 184 |
stop("specify exactly one of 'which' and 'x'") |
| 185 |
} |
| 186 |
which <- x |
| 187 |
for (n in seq_along(x)) which[n] <- max(which(m < x[n])) |
| 188 |
} else if (is.null(which)) { |
| 189 |
which <- 1L:k |
| 190 |
} |
| 191 |
if (any(which > k)) { |
| 192 |
stop(gettextf( |
| 193 |
"all elements of 'which' must be between 1 and %d", |
| 194 |
k |
| 195 |
), domain = NA) |
| 196 |
} |
| 197 |
border <- rep_len(border, length(which)) |
| 198 |
retval <- list() |
| 199 |
|
| 200 |
old_xpd <- par()["xpd"] |
| 201 |
par(xpd = xpd) |
| 202 |
|
| 203 |
for (n in seq_along(which)) { |
| 204 |
# this is to deal with the case when k is not defined for all values |
| 205 |
# and that we can not use the next k+1 value to decide on the height to use. |
| 206 |
next_k_height <- tree_heights[names(tree_heights) == k + 1] |
| 207 |
if (length(next_k_height) == 0) { |
| 208 |
next_k_height <- 0 |
| 209 |
prop_k_height <- 1 # use only the "k" now. |
| 210 |
# if(upper_rect == 0) upper_rect <- min(abs(diff(tree_heights))) / 2 |
| 211 |
} |
| 212 |
|
| 213 |
if (!horiz) { # the default |
| 214 |
xleft <- m[which[n]] + 0.66 |
| 215 |
# if(missing(lower_rect)) lower_rect <- par("usr")[3L] - strheight("W")*(max(nchar(labels(tree))) + 1) |
| 216 |
if (missing(lower_rect)) { |
| 217 |
lower_rect <- -max(strheight2(labels(tree))) |
| 218 |
dLeaf <- -0.75 * strheight("x") |
| 219 |
extra_space <- -strheight2("_") |
| 220 |
lower_rect <- lower_rect + dLeaf + extra_space |
| 221 |
} |
| 222 |
|
| 223 |
ybottom <- lower_rect |
| 224 |
xright <- m[which[n] + 1] + 0.33 |
| 225 |
# ytop = mean(tree_heights[(k - 1):k]) |
| 226 |
# ytop = tree_heights[k] + abs(ybottom) |
| 227 |
# ytop = mean(tree_heights[(k - 1):k]) + abs(ybottom) |
| 228 |
|
| 229 |
ytop <- max(tree_heights[names(tree_heights) == k]) * prop_k_height + |
| 230 |
next_k_height * (1 - prop_k_height) + |
| 231 |
upper_rect # tree_heights[k] + height_to_add # + abs(xright) |
| 232 |
} else { |
| 233 |
ybottom <- m[which[n]] + 0.66 |
| 234 |
# if(missing(lower_rect)) lower_rect <- par("usr")[2L] + strwidth("X")*(max(nchar(labels(tree))) + 1) |
| 235 |
# if(missing(lower_rect)) lower_rect <- -max(strwidth(labels(dend))) |
| 236 |
|
| 237 |
if (missing(lower_rect)) { |
| 238 |
lower_rect <- min(strwidth(labels(tree))) # notice the char length is negative! |
| 239 |
dLeaf <- 0.75 * strwidth("w") |
| 240 |
extra_space <- strwidth("_") |
| 241 |
lower_rect <- lower_rect + dLeaf + extra_space |
| 242 |
} |
| 243 |
|
| 244 |
xright <- lower_rect |
| 245 |
|
| 246 |
ytop <- m[which[n] + 1] + 0.33 |
| 247 |
# xleft = mean(tree_heights[(k - 1):k]) |
| 248 |
xleft <- |
| 249 |
tree_heights[names(tree_heights) == k] * prop_k_height + |
| 250 |
next_k_height * (1 - prop_k_height) + |
| 251 |
upper_rect # tree_heights[k] + height_to_add # + abs(xright) |
| 252 |
} |
| 253 |
rect(xleft, |
| 254 |
ybottom, |
| 255 |
xright, |
| 256 |
ytop, |
| 257 |
border = border[n], density = density, angle = angle, ... |
| 258 |
) |
| 259 |
|
| 260 |
# allow for a vectorized version of "text" |
| 261 |
if (!is.null(text)) { |
| 262 |
text((m[which[n]] + m[which[n] + 1] + 1) / 2, |
| 263 |
grconvertY(grconvertY(par("usr")[3L], "user", "ndc") + 0.02, "ndc", "user"), |
| 264 |
text[n], |
| 265 |
cex = text_cex, col = text_col |
| 266 |
) |
| 267 |
} |
| 268 |
|
| 269 |
retval[[n]] <- which(cluster == as.integer(names(clustab)[which[n]])) |
| 270 |
} |
| 271 |
|
| 272 |
|
| 273 |
par(xpd = old_xpd) |
| 274 |
invisible(retval) |
| 275 |
} |
| 276 |
|
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
|
| 283 |
|
| 284 |
|
| 285 |
|
| 286 |
|
| 287 |
|
| 288 |
#' @title Identify Clusters in a Dendrogram (not hclust) |
| 289 |
#' @export |
| 290 |
#' @description |
| 291 |
#' Just like \link{identify.hclust}: |
| 292 |
#' reads the position of the graphics pointer when the (first) |
| 293 |
#' mouse button is pressed. It then cuts the tree at the vertical |
| 294 |
#' position of the pointer and highlights the cluster containing |
| 295 |
#' the horizontal position of the pointer. Optionally a function is applied |
| 296 |
#' to the index of data points contained in the cluster. |
| 297 |
#' |
| 298 |
#' @param x a \link{dendrogram} object. |
| 299 |
#' @param FUN (optional) function to be applied to the index numbers of the |
| 300 |
#' data points in a cluster (see 'Details' below). |
| 301 |
#' @param N the maximum number of clusters to be identified. |
| 302 |
#' @param MAXCLUSTER the maximum number of clusters that can be produced by |
| 303 |
#' a cut (limits the effective vertical range of the pointer). |
| 304 |
#' @param DEV.FUN (optional) integer scalar. If specified, the corresponding |
| 305 |
#' graphics device is made active before FUN is applied. |
| 306 |
#' @param horiz logical (FALSE), indicating if the rectangles |
| 307 |
#' should be drawn horizontally or not (for when using |
| 308 |
#' plot(dend, horiz = TRUE) ) . |
| 309 |
#' @param stop_if_out logical (default is FALSE). This default makes the function |
| 310 |
#' NOT stop if k of the locator is outside the range (this default is different than the behavior |
| 311 |
#' of the identify.hclust function - but it is nicer for the user.). |
| 312 |
#' @param ... further arguments to FUN. |
| 313 |
#' @details |
| 314 |
#' By default clusters can be identified using the mouse and an invisible |
| 315 |
#' list of indices of the respective data points is returned. |
| 316 |
#' If FUN is not NULL, then the index vector of data points is passed to this |
| 317 |
#' function as first argument, see the examples below. The active |
| 318 |
#' graphics device for FUN can be specified using DEV.FUN. |
| 319 |
#' The identification process is terminated by pressing any mouse button other |
| 320 |
#' than the first, see also identify. |
| 321 |
#' @seealso |
| 322 |
#' \link{identify.hclust}, |
| 323 |
#' \link{rect.hclust}, \link{order.dendrogram}, \link{cutree.dendrogram} |
| 324 |
#' @return |
| 325 |
#' (Invisibly) returns a list where each element contains a vector |
| 326 |
#' of data points contained in the respective cluster. |
| 327 |
#' @source |
| 328 |
#' This function is based on \link{identify.hclust}, with slight modifications |
| 329 |
#' to have it work with a dendrogram, as well as adding "horiz" |
| 330 |
#' @examples |
| 331 |
#' |
| 332 |
#' \dontrun{ |
| 333 |
#' set.seed(23235) |
| 334 |
#' ss <- sample(1:150, 10) |
| 335 |
#' hc <- iris[ss, -5] %>% |
| 336 |
#' dist() %>% |
| 337 |
#' hclust() |
| 338 |
#' dend <- hc %>% as.dendrogram() |
| 339 |
#' |
| 340 |
#' plot(dend) |
| 341 |
#' identify(dend) |
| 342 |
#' |
| 343 |
#' plot(dend, horiz = TRUE) |
| 344 |
#' identify(dend, horiz = TRUE) |
| 345 |
#' } |
| 346 |
identify.dendrogram <- function(x, FUN = NULL, N = 20, MAXCLUSTER, DEV.FUN = NULL, |
| 347 |
horiz = FALSE, |
| 348 |
stop_if_out = FALSE, |
| 349 |
...) { |
| 350 |
|
| 351 |
# In tree_heights I am removing the first element |
| 352 |
# in order to be consistant with rect.hclust |
| 353 |
x_heights <- heights_per_k.dendrogram(x)[-1] |
| 354 |
# this is like rev(x$height) |
| 355 |
# tree_order <- order.dendrogram(tree) |
| 356 |
if (missing(MAXCLUSTER)) MAXCLUSTER <- nleaves(x) |
| 357 |
|
| 358 |
cluster <- cutree(x, k = 2:MAXCLUSTER) |
| 359 |
retval <- list() |
| 360 |
oldk <- NULL |
| 361 |
oldx <- NULL |
| 362 |
DEV.x <- grDevices::dev.cur() |
| 363 |
for (n in 1L:N) { |
| 364 |
grDevices::dev.set(DEV.x) |
| 365 |
X <- locator(1) |
| 366 |
if (horiz) { |
| 367 |
tmp <- X$x |
| 368 |
X$x <- X$y |
| 369 |
X$y <- tmp |
| 370 |
} |
| 371 |
|
| 372 |
if (is.null(X)) { |
| 373 |
break |
| 374 |
} |
| 375 |
k <- min(which(x_heights < X$y), MAXCLUSTER) |
| 376 |
k <- max(k, 2) |
| 377 |
if (!is.null(oldx)) { |
| 378 |
rect.dendrogram(x, |
| 379 |
k = oldk, x = oldx, |
| 380 |
cluster = cluster[, oldk - 1], |
| 381 |
border = "grey", horiz = horiz, stop_if_out = stop_if_out |
| 382 |
) |
| 383 |
} |
| 384 |
retval[[n]] <- unlist(rect.dendrogram(x, |
| 385 |
k = k, x = X$x, |
| 386 |
cluster = cluster[, k - 1], |
| 387 |
border = "red", horiz = horiz, stop_if_out = stop_if_out |
| 388 |
)) |
| 389 |
if (!is.null(FUN)) { |
| 390 |
if (!is.null(DEV.FUN)) { |
| 391 |
grDevices::dev.set(DEV.FUN) |
| 392 |
} |
| 393 |
retval[[n]] <- FUN(retval[[n]], ...) |
| 394 |
} |
| 395 |
oldx <- X$x |
| 396 |
oldk <- k |
| 397 |
} |
| 398 |
grDevices::dev.set(DEV.x) |
| 399 |
invisible(retval) |
| 400 |
} |