Generate pairs of bright and dark colours for ggplot2

colors, ggplot2, r

Solution

Here is a vectorized function that you can use. The idea is to convert RGB to HSV, where V corresponds to brightness and then go back to RGB:

library(grDevices)
# Every element of r, g, b must be in [0, 255]
# Every element of conv[[3]] must be in [0, 1], 1 is highest brightness
brightness <- function(r, g, b, factor) {
  conv <- as.list(as.data.frame(t(rgb2hsv(r, g, b))))
  conv[[3]] <- pmin(1, conv[[3]] * factor)
  do.call(hsv, conv)
}

# Reducing brightness by 20%
brightness(55, 100, 150, 0.8)
#[1] "#2C5078"

# Increasing by 20%
brightness(55, 100, 150, 1.2)
#[1] "#4278B4"

brightness(55, 100, 150, c(0.8, 1.2))
#[1] "#2C5078" "#4278B4"

x <- rep(LETTERS[1:2], 5)
qplot(x = x, geom = "bar", fill = x) + 
  scale_fill_manual(values = brightness(55, 100, 150, c(0.5, 1.5)))

See `?rgb2hsv`, `?hsv` and wiki for more details.

Edit: according to your edit it seems that you prefer using names of colours and direct values of brightness. In that case a vectorized function would look very similarly:

# Usage: brightness("red", c(0.1, 0.3, 0.5, 1))
brightness <- function(rgbcol, v) {
  conv <- as.list(as.data.frame(t(rgb2hsv(col2rgb(rgbcol)))))
  conv[[3]] <- v
  do.call(hsv, conv)
}

set.seed(19)
df <- data.frame(a = rlnorm(100), b = 1:10, c = rep(LETTERS[1:10], each = 10))
ggplot(df, aes(x = b, y = a, fill = c)) + geom_area() + theme_bw() +
  scale_fill_manual(values = brightness("red", seq(0.1, 0.7, length = 10)))

Problem

``` brewer.pal(n=8,name="Paired") ``` Can create up to eight colour pairs, but only few of these colours are good for printing. Is there a more flexible function that will generate a dark pendant? The darker one should - look like the same colour in dark - well printable - easy to distinguish from the bright one Is there a colourbrewer tool that can already solve that? ``` > dark("red") [1] "FF5555" ``` I figured out this function, but it can only handle single colours, not a vector. This function would be a nice solution, if it could be "vectorized". ``` setbrightness <- function(rgbcolour, brightness) { ## usage: setbrightness(col2rgb("red", 0.2) thiscolour <- rgb2hsv(rgbcolour) return(hsv(h=thiscolour[1], s=thiscolour[2], v=brightness)) } ```

Original source