2

Suppose I have this vector of colors in hex code (in R):

colors <- c("#62B200","#FF6C91","#F57962","#00C1A9","#EE8044")

I'm looking for a way to expand each color with n darker shades of it (i.e., pulled towards black).

So for example, if n = 2, this will be the expanded colors data.frame:

expanded.colors.df <- data.frame(original.color = c("#62B200","#62B200","#FF6C91","#FF6C91","#F57962","#F57962","#00C1A9","#00C1A9","#EE8044","#EE8044"),
                                 expanded.color = c("#62B200","#58A000","#FF6C91","#E56182","#F57962","#DC6C58","#00C1A9","#00AD98","#EE8044","#D6733D"))

I took these shades from here, which for a given color input gives a list of shades of it.

Any idea if there's an R function to achieve this?

enter image description here

dan
  • 6,048
  • 10
  • 57
  • 125

1 Answers1

2

For what it's worth:

library(tidyverse)

colors <- c("#62B200","#FF6C91","#F57962","#00C1A9","#EE8044")

#darken each color n times in increments of steps towards black
ExpandColors <- function(colors, n, steps = 11){
  if(n <= steps){
    suppressWarnings({
      sapply(colors, function(x){colorRampPalette(c(x, "#000000"))(steps)}) %>% 
        as.data.frame() %>% 
        filter(row_number() <= n) %>% 
        gather(key = original.color, value = expanded.color)
    })
  }else{
    warning("Select n < steps!")
  }
}

ExpandColors(colors, n = 2)

       original.color expanded.color
1         #62B200        #62B200
2         #62B200        #58A000
3         #FF6C91        #FF6C91
4         #FF6C91        #E56182
5         #F57962        #F57962
6         #F57962        #DC6C58
7         #00C1A9        #00C1A9
8         #00C1A9        #00AD98
9         #EE8044        #EE8044
10        #EE8044        #D6733D
Jordo82
  • 796
  • 4
  • 14
  • I think this one need an extra library, doesn't it? I've got a pure javascript solution down there. – Janos Vinceller Oct 19 '20 at 13:14
  • /** from https://stackoverflow.com/questions/5623838/rgb-to-hex-and-hex-to-rgb **/ function componentToHex(c) ... function rgbToHex(r, g, b) ... function hexToRgb(hex) ... function one(comp, shade) { return Math.round((255 - comp) * shade / 10) + comp; } /** Computes the shade. basecolor is a hex color like '#fec810', shade is from 0 to 9 **/ function computeColorShade(basecolor, shade) { let rgb = hexToRgb(basecolor); let r = one(rgb.r); let g = one(rgb.g); let b = one(rgb.b); return rgbToHex(r,g,b); } – Janos Vinceller Oct 19 '20 at 13:16