Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to programmatically darken the color given RGB values?

Tags:

r

colors

rgb

Let's say I have the RGB values like this (in R, for example):

cols <- c("#CDE4F3","#E7F3D3","#F7F0C7","#EFCFE5","#D0D1E7")

Is there any way to programmatically derive another set of colors which is a darkened version of the former?

It doesn't have to be R.

like image 217
Alby Avatar asked May 13 '15 15:05

Alby


1 Answers

The question asks whether there is any way to programmatically darken colors. The problem is that there are many different ways, and they all yield different results. The specific outcome you obtain depends on the specific algorithm employed and the color space used.

The R package colorspace now provides a built-in function to darken colors, through the darken() function. This function uses a new "combined" colorspace we came up with which is a mix between HLS and HCL. (In brief, adjusts L in HCL space but adjusts C by taking a detour through HLS, while keeping H constant.)

To use this function, you need to install the current development version of colorspace:

install.packages("colorspace", repos = "http://R-Forge.R-project.org")

Then, try the following:

# original colors
cols <- c("#CDE4F3", "#E7F3D3", "#F7F0C7", "#EFCFE5", "#D0D1E7")

# darken 20%
cols_d2 <- darken(cols, 0.2)

# darken 40%
cols_d4 <- darken(cols, 0.4)

# plot
pal <- function(col, border = "light gray") {
  n <- length(col)
  plot(0, 0, type="n", xlim = c(0, 1), ylim = c(0, 1), axes = FALSE,
       xlab = "", ylab = "")
  rect(0:(n-1)/n, 0, 1:n/n, 1, col = col, border = border)
}

par(mfrow = c(3, 1), mar = c(1, 0, 2, 0))
pal(cols); mtext("original")
pal(cols_d2); mtext("20% darker")
pal(cols_d4); mtext("40% darker")

enter image description here

There are a couple of different color spaces and other adjustment options you can try, but the default should work in most cases.

To see the effect of darkening in different color spaces, consider what happens when we darken the same colors in HCL or HLS:

enter image description here

The HCL-darkened colors seem quite gray, and the HLS-darkened colors appear overly bright and colorful. However, depending on your specific application, you might want one of these outcomes.

like image 112
Claus Wilke Avatar answered Sep 24 '22 16:09

Claus Wilke