这是您可以使用的矢量化函数。想法是将RGB转换为HSV,其中V对应亮度,然后返回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)))
?rgb2hsv
有关更多详细信息,请参阅?hsv
和wiki。
编辑:根据您的编辑,您似乎更喜欢使用颜色名称和亮度的直接值。在这种情况下,矢量化函数看起来非常相似:
# 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)))