Debian Codegraph @

R/colored_dots.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
89 #' @title Add colored dots beside a dendrogram
90 #' @export
91 #' @description
92 #' Add colored dots next to a dendrogram, usually
93 #' corresponding to either clusters or some outside
94 #' categorization.
95 #' @param colors Coloring of the dots beside the dendrogram. Either a vector (one color per object)
96 #' or a matrix (can also be an array or a data frame)
97 #' with each column giving one group with color per object.
98 #' Each column will be plotted as a colored point (when horiz = FALSE)
99 #' under the dendrogram.
100 #' As long as the sort_by_labels_order paramter is TRUE (default), the colors vector/matrix should
101 #' be provided in the order of the original data order (and it will be re-ordered automatically to
102 #' the order of the dendrogram)
103 #' @param dend a dendrogram object. If missing, the colors are plotted without and re-ordering
104 #' (this assumes that the colors are already ordered based on the dend's labels)
105 #' This is also important in order to get the correct height/location of the colored dots
106 #' (i.e.: adjusting the y_scale and y_shift)
107 #' @param rowLabels Labels for the colorings given in \code{colors}. The labels will be printed to the
108 #' left of the color rows in the plot. If the argument is given, it must be a vector of length
109 #' equal to the number of columns in \code{colors}. If not given, \code{names(colors)}
110 #' will be used if available. If not, sequential numbers
111 #' starting from 1 will be used.
112 #' @param cex.rowLabels Font size scale factor for the row labels. See \code{\link[graphics]{par}}.
113 #' @param add logical(TRUE), should the colored dots be added to an existing
114 #' dendrogram plot?
115 #' @param y_scale how much should the dots be stretched on the y axis?
116 #' If no dend is supplied - the default will be 1
117 #' @param y_shift where should the dots be plotted underneath the x axis?
118 #' By default it will try to locate the dots underneath the labels (it may miss,
119 #' in which case you would need to enter a number manually)
120 #' If no dend is supplied - the default will be 0
121 #' @param text_shift a dendrogram object
122 #' @param sort_by_labels_order logical(TRUE) - if TRUE (default), then the order of the
123 #' colored dots will be sorted based on the order needed to change the original
124 #' order of the observations to the current order of the labels in the dendrogram.
125 #' If FALSE the colored dots are plotted as-is, based on the order
126 #' of the colors vector.
127 #' @param horiz logical (FALSE by default). Set to TRUE when using plot(dend, horiz = TRUE)
128 #' @param dot_size numeric (1 by default). Passed to cex argument in points
129 #' @param ... ignored at this point.
130 #' @author Steve Horvath \email{SHorvath@@mednet.ucla.edu},
131 #' Tal Galili \email{Tal.Galili@@gmail.com},
132 #' Peter Langfelder \email{Peter.Langfelder@@gmail.com},
133 #' Chase Clark \email{chasec288@@gmail.com}
134 #' @details
135 #' The reason you might choose colored_dots over colored_bars is when you have
136 #' a lot of group types and/or a really large dendrogram.
137 #' Hint: Make a group for each categorical factor and color it one color when true,
138 #' and assign a fully transparent color when false.
139 #'
140 #' You will often need to adjust the y_scale, y_shift and the text_shift
141 #' parameters, in order to get the dots in the location you would want.
142 #'
143 #' (This can probably be done automatically, but will require more work.
144 #' since it has to do with the current mar settings,
145 #' the number of groups, and each computer's specific graphic device.
146 #' patches for smarter defaults will be appreciated)
147 #' @return
148 #' An invisible vector/matrix with the ordered colors.
149 #'
150 #' @source
151 #' This function is based on the \link[moduleColor]{plotHclustColors} from the
152 #' {moduleColor} R package. It was modified so that it would
153 #' work with dendrograms (and not just hclust objects), as well allow to
154 #' add the colored dots on top of an existing plot (and not only as a seperate plot).
155 #'
156 #' See: \url{https://cran.r-project.org/package=moduleColor}
157 #' For more details.
158 #'
159 #' @seealso
160 #' \link{branches_attr_by_clusters},
161 #' \link[WGCNA]{plotDendroAndColors}
162 #' @examples
163 #'
164 #' rows_picking <- c(1:5, 25:30)
165 #' dend <- (iris[rows_picking, -5] * 10) %>%
166 #' dist() %>%
167 #' hclust() %>%
168 #' as.dendrogram()
169 #' odd_numbers <- rows_picking %% 2
170 #' cols <- c("red", "white")[odd_numbers + 1]
171 #' plot(dend)
172 #' colored_dots(cols, dend)
173 #' # Example of adjusting postion of dots
174 #' plot(dend)
175 #' colored_dots(cols, dend,
176 #' y_shift = -1,
177 #' rowLabels = "Odd\n numbers"
178 #' )
179 #'
180 #'
181 #'
182 #' rows_picking <- c(1:5, 25:30)
183 #' dend <- (iris[rows_picking, -5] * 10) %>%
184 #' dist() %>%
185 #' hclust() %>%
186 #' as.dendrogram()
187 #' odd_numbers <- rows_picking %% 2
188 #' # For leaves that shouldn't have dots, make them the same color as the background,
189 #' # or set the alpha value to fully transparant
190 #' cols <- c("black", "white")[odd_numbers + 1]
191 #' # scale is off
192 #' plot(dend)
193 #' colored_dots(cols, dend)
194 #' # move and scale a bit
195 #' plot(dend)
196 #' colored_dots(cols, dend,
197 #' y_shift = -1,
198 #' rowLabels = "Odd\n numbers"
199 #' )
200 #' # Now let's cut the tree and add that info to the plot:
201 #' k2 <- cutree(dend, k = 2)
202 #' cols2 <- c("#1b9e77", "#d95f02")[k2]
203 #'
204 #' par(mar = c(5, 6, 1, 1))
205 #' plot(dend)
206 #' colored_dots(cbind(cols2, cols), dend,
207 #' rowLabels = c("2 clusters", "Even numbers")
208 #' )
209 #'
210 #' # The same, but with an horizontal plot!
211 #' par(mar = c(6, 2, 2, 4))
212 #' plot(dend, horiz = TRUE)
213 #' colored_dots(cbind(cols2, cols), dend,
214 #' rowLabels = c("2 clusters", "Even numbers"),
215 #' horiz = TRUE
216 #' )
217 #'
218 #' # ==============================
219 #' # ==============================
220 #'
221 #' ## mtcars example
222 #'
223 #' # Create the dend:
224 #' dend <- as.dendrogram(hclust(dist(mtcars)))
225 #'
226 #' # Get all company names
227 #' comp_names <- unlist(lapply(rownames(mtcars), function(x) strsplit(x, " ")[[1]][[1]]))
228 #' # Get the top three occurring companies
229 #' top_three <- sort(table(comp_names), decreasing = TRUE)[1:3]
230 #' # Match the top three companies to where they are found in the dendrogram labels
231 #' top_three <- sapply(names(top_three), function(x) grepl(x, labels(dend)))
232 #' top_three <- as.data.frame(top_three)
233 #' # "top_three" is now a data frame of the top three companies as columns.
234 #' # Each column represents a vector (rows) which is the length of labels(dend).
235 #' # The vector has values TRUE and FALSE, for whether the company name matched
236 #' # labels(dend)[i]
237 #'
238 #' # Colorblind friendly vector of HEX colors
239 #' colorblind_friendly <- c("#1b9e77", "#d95f02", "#7570b3")
240 #'
241 #' # If we run the for-loop on "top_three" we will turn the vectors into a character-type too early,
242 #' # so make a copy to "colored_dataframe" which we will work on
243 #' colored_dataframe <- top_three
244 #'
245 #' for (i in 1:3) {
246 #' # This replaces TRUE values with a color from our vector of colors
247 #' colored_dataframe[top_three[, i], i] <- colorblind_friendly[[i]]
248 #' # This replaces FALSE values with black HEX, but fully transparent (invisible on plot)
249 #' colored_dataframe[!top_three[, i], i] <- "#00000000"
250 #' }
251 #'
252 #' # Color branches and labels by "cutting" the dendrogram at an arbitrary height
253 #' dend <- color_branches(dend, h = 170)
254 #' dend <- color_labels(dend, h = 170)
255 #'
256 #' ### plots
257 #' par(mar = c(12, 4, 1, 1))
258 #' plot(dend)
259 #' colored_dots(colored_dataframe, dend,
260 #' rowLabels = colnames(colored_dataframe), horiz = FALSE, sort_by_labels_order = FALSE
261 #' )
262 #' # Show a dotted line where tree was "cut"
263 #' abline(h = 170, lty = 3)
264 #'
265 #' # horiz version:
266 #' par(mar = c(4, 1, 1, 12))
267 #' plot(dend, horiz = TRUE)
268 #' colored_dots(colored_dataframe, dend,
269 #' rowLabels = colnames(colored_dataframe), horiz = TRUE, sort_by_labels_order = FALSE
270 #' )
271 #' # Show a dotted line where the tree was "cut"
272 #' abline(v = 170, lty = 3)
273 colored_dots <- function(colors, dend, rowLabels = NULL, cex.rowLabels = 0.9,
274 add = TRUE,
275 y_scale, y_shift,
276 text_shift = 1,
277 sort_by_labels_order = TRUE,
278 horiz = FALSE,
279 # below_labels = TRUE,
280 dot_size = 1,
281 ...) {
282 # should either be a vector or a matrix (it could also work with data.frames)
283 # if(!(is.vector(colors) | is.matrix(colors))) stop("colors must be either a vector or a matrix")
284
285
286 # number of color boxes per row (i.e.: number of dend leaves)
287 n_colors <- if (is.null(dim(colors))) length(colors) else nrow(colors)
288 # number of rows (groups) of colors
289
290 n_groups <- if (is.null(dim(colors))) 1 else ncol(colors)
291
292
293
294 if (!missing(dend)) {
295 # make sure we are working with a dend:
296 if (is.hclust(dend)) dend <- as.dendrogram(dend)
297
298 if (!is.dendrogram(dend)) stop("'dend' should be a dendrogram.")
299 # get labels' order:
300 # dend_size <- nleaves(dend)
301 dend_labels <- labels(dend)
302 dend_order <- order.dendrogram(dend)
303 } else { # if we ARE missing dend
304
305 dend_labels <- rep("W", n_colors) # assume all labels are W
306 dend_order <- seq_len(n_colors)
307 }
308
309 if (!sort_by_labels_order) dend_order <- seq_len(n_colors)
310
311 # # Get y_shift to be underneath the labels
312 # if(!horiz) {
313 # if(missing(y_shift)) y_shift <- -max(strwidth(dend_labels))+par()$usr[3L]-2*strheight("x") # a bit of a hack, oh well...
314 # if(missing(y_scale)) y_scale <- median(strheight(dend_labels)) * nrow_colors * .8
315 # } else {
316 # if(missing(y_shift)) y_shift <- max(abs(strwidth(dend_labels)))+par()$usr[3L]-3*strwidth("x") # a bit of a hack, oh well...
317 # if(missing(y_scale)) y_scale <- median(abs(strwidth(dend_labels))) * nrow_colors * .8
318 # }
319
320
321 # Get y_shift to be underneath the labels
322 if (!horiz) {
323 # We shift y with the max height of the rotated labels + plot region + one row of values (the height of X)
324 if (missing(y_shift)) y_shift <- -max_labels_height(dend_labels) + par("usr")[3L] - strheight("X")
325
326
327 if (missing(y_scale)) y_scale <- strheight("X") * n_groups
328 } else {
329 if (missing(y_shift)) y_shift <- -(min(strwidth(dend_labels)) + par("usr")[2L] + strwidth("X"))
330
331
332 if (missing(y_scale)) y_scale <- strwidth("X") * n_groups
333 }
334
335
336
337 # moving the y location and scale of the dots
338 # this allows us to have it underneath the dend
339 # in a way that would look nice.
340 # if(missing(y_scale)) y_scale <- 1
341
342 # this makes sure that the original shift we had is always compared to the top of the dots (instead of the bottom)
343 # the if-else lowers the y further, to make sure it is below the labels.
344 y_shift <- y_shift - y_scale
345 # - if(below_labels) max(strheight(labels(dend))) else 0
346
347 colors <- as.matrix(colors)
348 dimC <- dim(colors)
349
350 if (is.null(rowLabels) & (length(dimnames(colors)[[2]]) == dimC[2])) rowLabels <- names(as.data.frame(colors))
351
352
353 op <- options()
354 pr <- par(no.readonly = TRUE)
355
356 options(stringsAsFactors = FALSE)
357 # par(mar = c(0, 4.1, 0, 2.1))
358 par(xpd = TRUE)
359
360 if (length(dend_order) != dimC[1]) {
361 stop("ERROR: length of colors vector not compatible with number of objects in the hierarchical tree.")
362 }
363 C <- colors[dend_order, ] # new colors vector
364 C <- as.matrix(C)
365 step <- 1 / (n_colors - 1)
366 ystep <- 1 / n_groups
367
368 if (!add) {
369 barplot(height = 1, col = "white", border = FALSE, space = 0, axes = FALSE, ...)
370 }
371
372
373 charWidth <- strwidth("W") / 2
374 charHeight <- strheight("W") / 2
375 for (j in 1:n_groups)
376 {
377 ind <- (1:n_colors)
378 xl <- (ind - 1.5) * step # locations of the x left
379 xr <- (ind - 0.5) * step
380 yb <- rep(ystep * (j - 1), n_colors)
381 yt <- rep(ystep * j, n_colors)
382
383 if (add) {
384 xl <- rescale(xl, to = c(1 - .5, n_colors - .5))
385 xr <- rescale(xl, to = c(1 + .5, n_colors + .5))
386 yb <- yb * y_scale + y_shift
387 yt <- yt * y_scale + y_shift
388 }
389
390
391
392
393
394
395
396 if (horiz) {
397 # Instead of rectangles, put in points at 1/2 x and y coordinates
398 # rect(-yb, xl, -yt, xr, col = as.character(C[, j]),
399 # border = as.character(C[, j]))
400
401 points((-yb + (-yt)) / 2, (xl + xr) / 2, pch = 19, col = as.character(C[, j]), cex = dot_size)
402
403
404 # plot the rowLabels text:
405 par(srt = 90)
406
407 if (is.null(rowLabels)) {
408 s <- as.character(j)
409
410 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)
411 # text(as.character(j), pos=2, x= -charWidth -0.5*step, y=ystep*(j-0.5), cex=cex.rowLabels, xpd = TRUE);
412 } else {
413 s <- rowLabels[j]
414
415 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)
416 # text(rowLabels[j], pos=2, x= -charWidth -0.5*step, y=ystep*(j-0.5), cex=cex.rowLabels, xpd = TRUE);
417 }
418 } else { # default
419 # Instead of rectangles, put in points at 1/2 x and y coordinates
420 # rect(xl, yb, xr, yt, col = as.character(C[, j]),
421 # border = as.character(C[, j]))
422 points((xl + xr) / 2, (yb + yt) / 2, pch = 19, col = as.character(C[, j]), cex = dot_size)
423
424
425 if (is.null(rowLabels)) {
426 text(as.character(j), pos = 2, x = charWidth * text_shift, y = ystep * (j - 0.5) * y_scale + y_shift, cex = cex.rowLabels)
427 # text(as.character(j), pos=2, x= -charWidth -0.5*step, y=ystep*(j-0.5), cex=cex.rowLabels, xpd = TRUE);
428 } else {
429 text(rowLabels[j], pos = 2, x = charWidth * text_shift, y = ystep * (j - 0.5) * y_scale + y_shift, cex = cex.rowLabels)
430 # text(rowLabels[j], pos=2, x= -charWidth -0.5*step, y=ystep*(j-0.5), cex=cex.rowLabels, xpd = TRUE);
431 }
432 }
433 }
434 # we start j from 0 so that it will add a line below the dots (and not just above them)
435
436
437 # Adds lines to seperate the clusters
438 for (j in 0:n_groups) {
439 the_x <- rescale(c(0, 1), to = c(1 - .5, n_colors + .5))
440
441 if (horiz) {
442 lines(y = the_x, x = -(c(ystep * j, ystep * j) * y_scale + y_shift))
443 } else {
444 lines(x = the_x, y = c(ystep * j, ystep * j) * y_scale + y_shift)
445 }
446 }
447
448
449
450 options(op) # reset (all) initial options
451 par(pr) # suppressWarnings(par(pr))
452
453 return(invisible(C))
454 }