Search code examples
rmatrixhexcolor-palette

How to mix optimally a color palette (n=5) with a second color palette (n=4) plus a luminance variable (n=4) in a matrix (total 5*4*4=80 colors)


Using R, would there be a way, whatever it is, to mix a red palette (n=5 levels) with an orange palette (n=4 levels), and to mix each the 5x4 resulting colors according to a luminance (or transparency/opacity) variable (n=4 levels) so that the 5x4x4=80 colors are optimally distinct from each other (i.e., evenly distributed), and then get the corresponding colors hexadecimal codes?

Below, an excel overview of the colors/luminance matrix to mix.

Thanks a lot

Matrix of colors


Solution

  • I did not find an appropriate way/function to mix evenly the red and orange palettes. Hence I looked for the best mixes, one by one, thanks to the excellent website trycolors.com/custom). Then, I adjusted the 4 contrast levels using the swatchplot function (darken option) from the colorspace package, as follows:

    # select your gradient colors (hexadecimal codes) and optimize them: https://trycolors.com/custom/
    library(colorspace)
    # better visualization for comparison of color shades with this layout:
    a0_hex <- c(
      "#ffffdd","#fdf3be","#ffea90","#fbdb7a",
      "#f9ceca","#fdc2ae","#ffa98a","#f99662",
      "#fb9991","#f58473","#ef6e44","#e56223",
      "#f15854","#ef3418","#dd3818","#cc3a01",
      "#d70303","#ca0303","#ba0808","#a60505")
    
    # darken (or lighten) colors: https://colorspace.r-forge.r-project.org/reference/lighten.html
    a1_dark <-
      swatchplot(
        "  0%" = a0_hex,
        " 10%" =  darken(a0_hex, 0.1),
        " 20%" =  darken(a0_hex, 0.2),
        " 30%" =  darken(a0_hex, 0.3),
        nrow = 4, off = c(0, 0))
    
    a2_dark <- as.data.frame(a1_dark)
    a2_dark
    
    # rearrange the order of colors as required
    library(tidyr)  # From long to wide table: https://mgimond.github.io/ES218/Week03b.html
    a3_red_0 <- a2_dark %>% select(1:4) %>% pivot_longer(cols=1:4, names_to = "col", values_to = "hex")
    a3_red_1 <- a2_dark %>% select(5:8) %>% pivot_longer(cols=1:4, names_to = "col", values_to = "hex")
    a3_red_2 <- a2_dark %>% select(9:12) %>% pivot_longer(cols=1:4, names_to = "col", values_to = "hex")
    a3_red_3 <- a2_dark %>% select(13:16) %>% pivot_longer(cols=1:4, names_to = "col", values_to = "hex")
    a3_red_4 <- a2_dark %>% select(17:20) %>% pivot_longer(cols=1:4, names_to = "col", values_to = "hex")
    
    # join and get all hex codes in one single column
    a3_red_all <- rbind(a3_red_0, a3_red_1, a3_red_2, a3_red_3, a3_red_4) %>% select(!col)
    
    # show the 5x4x4 = 80 colors
    windows(200, 1800, pointsize = 12, xpos = 650, ypos = 25)
    swatchplot(a3_red_all, nrow = 80, off = c(0, 0))
    

    enter image description here