Debian Codegraph @

R/colored_bars.R

raw
1 # Copyright (C) Tal Galili
2 #
3 # This file is part of dendextend.
4 #
5 # dendextend is free software: you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation, either version 2 of the License, or
8 # (at your option) any later version.
9 #
10 # dendextend is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # A copy of the GNU General Public License is available at
16 # http://www.r-project.org/Licenses/
17 #
18
19
20 # source: https://stackoverflow.com/questions/5468280/scale-a-series-between-two-points-in-r
21 # from the {scales} package
22 # library("scales"); rescale
23
24 zero_range <- function(x, tol = .Machine$double.eps * 100) {
25 if (length(x) == 1) {
26 return(TRUE)
27 }
28 if (length(x) != 2) {
29 stop("x must be length 1 or 2")
30 }
31 if (any(is.na(x))) {
32 return(NA)
33 }
34 if (x[1] == x[2]) {
35 return(TRUE)
36 }
37 if (all(is.infinite(x))) {
38 return(FALSE)
39 }
40 m <- min(abs(x))
41 if (m == 0) {
42 return(FALSE)
43 }
44 abs((x[1] - x[2]) / m) < tol
45 }
46
47 rescale <- function(x, to = c(0, 1), from = range(x, na.rm = TRUE)) {
48 if (zero_range(from) || zero_range(to)) {
49 return(rep(mean(to), length(x)))
50 }
51 (x - from[1]) / diff(from) * diff(to) + to[1]
52 }
53
54
55
56
57
58
59 # if(T) 2 else 1
60 # if(F) 2 else 1
61
62
63
64 # This function is require in order to know the height of the rotated labels in the dendrogram!
65 # Thanks to Prof. Brian Ripley
66 # # https://r.789695.n4.nabble.com/strwidth-and-strheight-for-rotated-text-td839105.html
67 rotated_str_dim <- function(s) {
68 cha <- s
69 xusr <- par("usr")
70 xh <- strwidth(cha, cex = par("cex"))
71 yh <- strheight(cha, cex = par("cex")) * 5 / 3
72 tmp <- xh
73 xh <- yh / (xusr[4] - xusr[3]) * par("pin")[2]
74 xh <- xh / par("pin")[1] * (xusr[2] - xusr[1])
75 yh <- tmp / (xusr[2] - xusr[1]) * par("pin")[1]
76 yh <- yh / par("pin")[2] * (xusr[4] - xusr[3])
77 c(xh = xh, yh = yh)
78 }
79 V_rotated_str_dim <- Vectorize(rotated_str_dim)
80 max_labels_height <- function(s) {
81 # s <- paste0(dend_labels, " ")
82 a <- V_rotated_str_dim(s)
83 max(a["yh", ])
84 }
85
86
87
88 #' @title Add colored bars to a dendrogram
89 #' @export
90 #' @description
91 #' Add colored bars to a dendrogram, usually
92 #' corresponding to either clusters or some outside
93 #' categorization.
94 #' @param colors Coloring of objects on the dendrogram. Either a vector (one color per object)
95 #' or a matrix (can also be an array or a data frame)
96 #' with each column giving one group with color per object.
97 #' Each column will be plotted as a horizontal row of colors (when horiz = FALSE)
98 #' under the dendrogram.
99 #' As long as the sort_by_labels_order paramter is TRUE (default), the colors vector/matrix should
100 #' be provided in the order of the original data order (and it will be re-ordered automaticall to
101 #' the order of the dendrogram)
102 #' @param dend a dendrogram object. If missing, the colors are plotted without and re-ordering
103 #' (this assumes that the colors are already ordered based on the dend's labels)
104 #' This is also important in order to get the correct height/location of the colored bars
105 #' (i.e.: adjusting the y_scale and y_shift)
106 #' @param rowLabels Labels for the colorings given in \code{colors}. The labels will be printed to the
107 #' left of the color rows in the plot. If the argument is given, it must be a vector of length
108 #' equal to the number of columns in \code{colors}. If not given, \code{names(colors)}
109 #' will be used if available. If not, sequential numbers
110 #' starting from 1 will be used.
111 #' @param cex.rowLabels Font size scale factor for the row labels. See \code{\link[graphics]{par}}.
112 #' @param add logical(TRUE), should the colored bars be added to an existing
113 #' dendrogram plot?
114 #' @param y_scale how much should the bars be stretched on the y axis?
115 #' If no dend is supplied - the default will be 1
116 #' @param y_shift where should the bars be plotted underneath the x axis?
117 #' By default it will try to locate the bars underneath the labels (it may miss,
118 #' in which case you would need to enter a number manually)
119 #' If no dend is supplied - the default will be 0
120 #' @param text_shift a dendrogram object
121 #' @param sort_by_labels_order logical(TRUE) - if TRUE (default), then the order of the
122 #' colored bars will be sorted based on the order needed to change the original
123 #' order of the observations to the current order of the labels in the dendrogram.
124 #' If FALSE the colored bars are plotted as-is, based on the order
125 #' of the colors vector.
126 #' @param horiz logical (FALSE by default). Set to TRUE when using plot(dend, horiz = TRUE)
127 #' @param ... ignored at this point.
128 #' @author Steve Horvath \email{SHorvath@@mednet.ucla.edu},
129 #' Peter Langfelder \email{Peter.Langfelder@@gmail.com},
130 #' Tal Galili \email{Tal.Galili@@gmail.com}
131 #' @details
132 #' You will often needs to adjust the y_scale, y_shift and the text_shift
133 #' parameters, in order to get the bars in the location you would want.
134 #'
135 #' (this can probably be done automatically, but will require more work.
136 #' since it has to do with the current mar settings,
137 #' the number of groups, and each computer's specific graphic device.
138 #' patches for smarter defaults will be appreciated)
139 #' @return
140 #' An invisible vector/matrix with the ordered colors.
141 #'
142 #' @source
143 #' This function is based on the \link[moduleColor]{plotHclustColors} from the
144 #' {moduleColor} R package. It was modified so that it would
145 #' work with dendrograms (and not just hclust objects), as well allow to
146 #' add the colored bars on top of an existing plot (and not only as a seperate plot).
147 #'
148 #' See: \url{https://cran.r-project.org/package=moduleColor}
149 #' For more details.
150 #'
151 #' @seealso
152 #' \link{branches_attr_by_clusters},
153 #' \link[WGCNA]{plotDendroAndColors}
154 #' @examples
155 #'
156 #'
157 #' rows_picking <- c(1:5, 25:30)
158 #' dend <- (iris[rows_picking, -5] * 10) %>%
159 #' dist() %>%
160 #' hclust() %>%
161 #' as.dendrogram()
162 #' odd_numbers <- rows_picking %% 2
163 #' cols <- c("gold", "grey")[odd_numbers + 1]
164 #' # scale is off
165 #' plot(dend)
166 #' colored_bars(cols, dend)
167 #' # move and scale a bit
168 #' plot(dend)
169 #' colored_bars(cols, dend,
170 #' y_shift = -1,
171 #' rowLabels = "Odd\n numbers"
172 #' )
173 #' # Now let's cut the tree and add that info to the plot:
174 #' k2 <- cutree(dend, k = 2)
175 #' cols2 <- c("#0082CE", "#CC476B")[k2]
176 #' plot(dend)
177 #' colored_bars(cbind(cols2, cols), dend,
178 #' rowLabels = c("2 clusters", "Odd numbers")
179 #' )
180 #'
181 #' # The same, but with an horizontal plot!
182 #' par(mar = c(6, 2, 2, 4))
183 #' plot(dend, horiz = TRUE)
184 #' colored_bars(cbind(cols2, cols), dend,
185 #' rowLabels = c("2 clusters", "Odd numbers"),
186 #' horiz = TRUE
187 #' )
188 #'
189 #'
190 #'
191 #' # let's add clusters color
192 #' # notice how we need to play with the colors a bit
193 #' # this is because color_branches places colors from
194 #' # left to right. Which means we need to give colored_bars
195 #' # the colors of the items so that ofter sorting they would be
196 #' # from left to right. Here is how it can be done:
197 #' the_k <- 3
198 #' library(colorspace)
199 #' cols3 <- rainbow_hcl(the_k, c = 90, l = 50)
200 #' dend %>%
201 #' set("branches_k_color", k = the_k, with = cols3) %>%
202 #' plot()
203 #'
204 #' kx <- cutree(dend, k = the_k)
205 #' ord <- order.dendrogram(dend)
206 #' kx <- sort_levels_values(kx[ord])
207 #' kx <- kx[match(seq_along(ord), ord)]
208 #'
209 #' par(mar = c(5, 5, 2, 2))
210 #' plot(dend)
211 #' colored_bars(cbind(cols3[kx], cols2, cols), dend,
212 #' rowLabels = c("3 clusters", "2 clusters", "Odd numbers")
213 #' )
214 #'
215 #'
216 #'
217 #' ## mtcars example
218 #'
219 #' # Create the dend:
220 #' dend <- as.dendrogram(hclust(dist(mtcars)))
221 #'
222 #' # Create a vector giving a color for each car to which company it belongs to
223 #' car_type <- rep("Other", length(rownames(mtcars)))
224 #' is_x <- grepl("Merc", rownames(mtcars))
225 #' car_type[is_x] <- "Mercedes"
226 #' is_x <- grepl("Mazda", rownames(mtcars))
227 #' car_type[is_x] <- "Mazda"
228 #' is_x <- grepl("Toyota", rownames(mtcars))
229 #' car_type[is_x] <- "Toyota"
230 #' car_type <- factor(car_type)
231 #' n_car_types <- length(unique(car_type))
232 #' col_car_type <- colorspace::rainbow_hcl(n_car_types, c = 70, l = 50)[car_type]
233 #'
234 #' # extra: showing the various clusters cuts
235 #' k234 <- cutree(dend, k = 2:4)
236 #'
237 #' # color labels by car company:
238 #' labels_colors(dend) <- col_car_type[order.dendrogram(dend)]
239 #' # color branches based on cutting the tree into 4 clusters:
240 #' dend <- color_branches(dend, k = 4)
241 #'
242 #' ### plots
243 #' par(mar = c(12, 4, 1, 1))
244 #' plot(dend)
245 #' colored_bars(cbind(k234[, 3:1], col_car_type), dend,
246 #' rowLabels = c(paste0("k = ", 4:2), "Car Type")
247 #' )
248 #'
249 #' # horiz version:
250 #' par(mar = c(4, 1, 1, 12))
251 #' plot(dend, horiz = TRUE)
252 #' colored_bars(cbind(k234[, 3:1], col_car_type), dend,
253 #' rowLabels = c(paste0("k = ", 4:2), "Car Type"), horiz = TRUE
254 #' )
255 colored_bars <- function(colors, dend, rowLabels = NULL, cex.rowLabels = 0.9,
256 add = TRUE,
257 y_scale, y_shift,
258 text_shift = 1,
259 sort_by_labels_order = TRUE,
260 horiz = FALSE,
261 # below_labels = TRUE,
262 ...) {
263 # should either be a vector or a matrix (it could also work with data.frames)
264 # if(!(is.vector(colors) | is.matrix(colors))) stop("colors must be either a vector or a matrix")
265
266
267 # number of color boxes per row (i.e.: number of dend leaves)
268 n_colors <- if (is.null(dim(colors))) length(colors) else nrow(colors)
269 # number of rows (groups) of colors
270 n_groups <- if (is.null(dim(colors))) 1 else ncol(colors)
271
272
273
274 if (!missing(dend)) {
275 # make sure we are working with a dend:
276 if (is.hclust(dend)) dend <- as.dendrogram(dend)
277 if (!is.dendrogram(dend)) stop("'dend' should be a dendrogram.")
278 # get labels' order:
279 # dend_size <- nleaves(dend)
280 dend_labels <- labels(dend)
281 dend_order <- order.dendrogram(dend)
282 } else { # if we ARE missing dend
283 dend_labels <- rep("W", n_colors) # assume all labels are W
284 dend_order <- seq_len(n_colors)
285 }
286
287 if (!sort_by_labels_order) dend_order <- seq_len(n_colors)
288
289 # # Get y_shift to be underneath the labels
290 # if(!horiz) {
291 # if(missing(y_shift)) y_shift <- -max(strwidth(dend_labels))+par()$usr[3L]-2*strheight("x") # a bit of a hack, oh well...
292 # if(missing(y_scale)) y_scale <- median(strheight(dend_labels)) * nrow_colors * .8
293 # } else {
294 # if(missing(y_shift)) y_shift <- max(abs(strwidth(dend_labels)))+par()$usr[3L]-3*strwidth("x") # a bit of a hack, oh well...
295 # if(missing(y_scale)) y_scale <- median(abs(strwidth(dend_labels))) * nrow_colors * .8
296 # }
297
298
299 # Get y_shift to be underneath the labels
300 if (!horiz) {
301 # We shift y with the max height of the rotated labels + plot region + one row of values (the height of X)
302 if (missing(y_shift)) y_shift <- -max_labels_height(dend_labels) + par("usr")[3L] - strheight("X")
303 if (missing(y_scale)) y_scale <- strheight("X") * n_groups
304 } else {
305 if (missing(y_shift)) y_shift <- -(min(strwidth(dend_labels)) + par("usr")[2L] + strwidth("X"))
306 if (missing(y_scale)) y_scale <- strwidth("X") * n_groups
307 }
308
309
310
311 # moving the y location and scale of the bars
312 # this allows us to have it underneath the dend
313 # in a way that would look nice.
314 # if(missing(y_scale)) y_scale <- 1
315
316 # this makes sure that the original shift we had is always compared to the top of the bars (instead of the bottom)
317 # the if-else lowers the y further, to make sure it is below the labels.
318 y_shift <- y_shift - y_scale
319 # - if(below_labels) max(strheight(labels(dend))) else 0
320
321 colors <- as.matrix(colors)
322 dimC <- dim(colors)
323
324 if (is.null(rowLabels) & (length(dimnames(colors)[[2]]) == dimC[2])) rowLabels <- names(as.data.frame(colors))
325
326 op <- options()
327 pr <- par(no.readonly = TRUE)
328
329 options(stringsAsFactors = FALSE)
330 # par(mar = c(0, 4.1, 0, 2.1))
331 par(xpd = TRUE)
332
333 if (length(dend_order) != dimC[1]) {
334 stop("ERROR: length of colors vector not compatible with number of objects in the hierarchical tree.")
335 }
336 C <- colors[dend_order, ] # new colors vector
337 C <- as.matrix(C)
338 step <- 1 / (n_colors - 1)
339 ystep <- 1 / n_groups
340
341 if (!add) {
342 barplot(height = 1, col = "white", border = FALSE, space = 0, axes = FALSE, ...)
343 }
344
345
346 charWidth <- strwidth("W") / 2
347 charHeight <- strheight("W") / 2
348 for (j in 1:n_groups)
349 {
350 ind <- (1:n_colors)
351 xl <- (ind - 1.5) * step # locations of the x left
352 xr <- (ind - 0.5) * step
353 yb <- rep(ystep * (j - 1), n_colors)
354 yt <- rep(ystep * j, n_colors)
355
356 if (add) {
357 xl <- rescale(xl, to = c(1 - .5, n_colors - .5))
358 xr <- rescale(xl, to = c(1 + .5, n_colors + .5))
359 yb <- yb * y_scale + y_shift
360 yt <- yt * y_scale + y_shift
361 }
362
363 if (horiz) {
364 rect(-yb, xl, -yt, xr, col = as.character(C[, j]), border = as.character(C[, j]))
365
366 # plot the rowLabels text:
367 par(srt = 90)
368
369 if (is.null(rowLabels)) {
370 s <- as.character(j)
371 text(s, pos = 1, offset = 0.5, y = charHeight * text_shift - rotated_str_dim(s)[2] / 2, x = -(ystep * (j) * y_scale + y_shift), cex = cex.rowLabels)
372 # text(as.character(j), pos=2, x= -charWidth -0.5*step, y=ystep*(j-0.5), cex=cex.rowLabels, xpd = TRUE);
373 } else {
374 s <- rowLabels[j]
375 text(s, pos = 1, offset = 0.5, y = charHeight * text_shift - rotated_str_dim(s)[2] / 2, x = -(ystep * (j) * y_scale + y_shift), cex = cex.rowLabels)
376 # text(rowLabels[j], pos=2, x= -charWidth -0.5*step, y=ystep*(j-0.5), cex=cex.rowLabels, xpd = TRUE);
377 }
378 } else { # default
379 rect(xl, yb, xr, yt, col = as.character(C[, j]), border = as.character(C[, j]))
380
381 if (is.null(rowLabels)) {
382 text(as.character(j), pos = 2, x = charWidth * text_shift, y = ystep * (j - 0.5) * y_scale + y_shift, cex = cex.rowLabels)
383 # text(as.character(j), pos=2, x= -charWidth -0.5*step, y=ystep*(j-0.5), cex=cex.rowLabels, xpd = TRUE);
384 } else {
385 text(rowLabels[j], pos = 2, x = charWidth * text_shift, y = ystep * (j - 0.5) * y_scale + y_shift, cex = cex.rowLabels)
386 # text(rowLabels[j], pos=2, x= -charWidth -0.5*step, y=ystep*(j-0.5), cex=cex.rowLabels, xpd = TRUE);
387 }
388 }
389 }
390 # we start j from 0 so that it will add a line below the bars (and not just above them)
391
392
393 # Adds lines to seperate the clusters
394 for (j in 0:n_groups) {
395 the_x <- rescale(c(0, 1), to = c(1 - .5, n_colors + .5))
396 if (horiz) {
397 lines(y = the_x, x = -(c(ystep * j, ystep * j) * y_scale + y_shift))
398 } else {
399 lines(x = the_x, y = c(ystep * j, ystep * j) * y_scale + y_shift)
400 }
401 }
402
403
404
405 options(op) # reset (all) initial options
406 par(pr) # suppressWarnings(par(pr))
407
408 return(invisible(C))
409 }
410
411
412
413
414
415
416 #
417 # if(FALSE) {
418 #
419 #
420 #
421 # colored_bars(dend, the_cols[cutree(dend, k = the_k)], y_shift = -2)
422 # plot(1:5, pch = 19, cex = 2, col = the_cols)
423 #
424 # cutree(dend, k = the_k)[order.dendrogram(dend)]
425 #
426 # kx <- cutree(dend, k = the_k)
427 # ord <- order.dendrogram(dend)
428 # kx <- sort_levels_values(kx[ord])
429 # kx <- kx[match(seq_along(ord), ord)]
430 #
431 # library(colorspace)
432 # dend %>% set("branches_k_color", k = the_k, with = the_cols) %>% plot
433 # colored_bars(dend, cols3[kx], y_shift = -2)
434 #
435 #
436 #
437 #
438 # # of course the pattern we see is just fake.
439 #
440 # k4 <- cutree(dend, k = 4)
441 # plot(dend)
442 # colored_bars(dend, k4)
443 # library(colorspace)
444 # dend %>% set("branches_k_color", k = 4) %>% plot
445 # colored_bars(dend, rainbow_hcl(4)[c(4,2,3,1)][k4], y_shift = -2)
446 #
447 # the_k <- 5
448 # the_cols <- rainbow_hcl(the_k, c=90, l=50)
449 # dend %>% set("branches_k_color", k = the_k, with = the_cols) %>% plot
450 # colored_bars(dend, the_cols[cutree(dend, k = the_k)], y_shift = -2)
451 # plot(1:5, pch = 19, cex = 2, col = the_cols)
452 #
453 # cutree(dend, k = the_k)[order.dendrogram(dend)]
454 #
455 # kx <- cutree(dend, k = the_k)
456 # ord <- order.dendrogram(dend)
457 # kx <- sort_levels_values(kx[ord])
458 # kx <- kx[match(seq_along(ord), ord)]
459 #
460 # library(colorspace)
461 # dend %>% set("branches_k_color", k = the_k, with = the_cols) %>% plot
462 # colored_bars(dend, the_cols[kx], y_shift = -2)
463 #
464 # the_cols <- apply(cutree(dend, k = 2:5), 2, function(x) heat_hcl(5)[x])
465 #
466 # plot(dend, las = 1)
467 # colored_bars(dend, the_cols)
468 # plot(dend, las = 1)
469 # colored_bars(dend, the_cols,y_scale = 3, y_shift = -2)
470 #
471 # }