# color_dissimilarity

Measure the similarity of colors in a palette, and choose dissimilar colors from them.

seq_dissim_colors.R (1352B)

1 #' Choose maximally dissimilar colors sequentially
2 #'
3 #' This function chooses colors greedily, staring with the most dissimilar pair
4 #' and then choosing the color that is most dissimilar from the previously
5 #' chosen ones.
6 #'
7 #' @param dissim_mat A dissimilarity matrix
8 #'
9 #' @return The element IDs in decreasing similarity
10 #' @export
11 seq_dissim_colors <- function(dissim_mat) {
12   color_sequence <- rep(NA, ncol(dissim_mat))
13
14   # First, we'll find the column that has the pair of colors with the maximum
15   # dissimilarity and save that column as the "first" color we picked and store
16   # this column as a vector.
17   color_sequence[1] <- which.max(dissim_mat) %/% nrow(dissim_mat) + 1
18   dissim_vec <- dissim_mat[, color_sequence[1]]
19
20   for (i in seq(2, length(dissim_vec))) {
21     # Find the index of the maximum dissimilarity of the current vector and save
22     # it in the list of colors.
23     color_sequence[i] <- which.max(dissim_vec)
24
25     # Replace each element in this vector with the minimum of that element and the
26     # element with the same index in the newly selected color.
27     dissim_vec <- pmin(dissim_vec, dissim_mat[, color_sequence[i]])
28   }
29
30   # Add the color names if they're present in the dissimilarity matrix
31   if (!is.null(colnames(dissim_mat)))
32     names(color_sequence) <- colnames(dissim_mat)[color_sequence]
33
34   color_sequence
35 }