为ggplot2生成明亮和暗色对

时间:2012-12-02 01:28:27

标签: r colors ggplot2

brewer.pal(n=8,name="Paired")

最多可以创建八个颜色对,但这些颜色中只有少数适​​合打印。 是否有更灵活的功能会产生黑暗的坠饰? 较暗的应该

  • 在黑暗中看起来像是相同的颜色
  • 可打印
  • 容易与明亮区分

是否有可以解决这个问题的colourbrewer工具?

> dark("red")
[1] "FF5555"

我想出了这个功能,但它只能处理单一颜色,而不能处理矢量。如果它可以“矢量化”,这个函数将是一个很好的解决方案。

setbrightness <- function(rgbcolour, brightness) {
  ## usage: setbrightness(col2rgb("red", 0.2)
  thiscolour <- rgb2hsv(rgbcolour)
  return(hsv(h=thiscolour[1], s=thiscolour[2], v=brightness))
}

1 个答案:

答案 0 :(得分:10)

这是一个可以使用的矢量化函数。我们的想法是将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)))

enter image description here

有关详细信息,请参阅?rgb2hsv?hsvwiki

编辑根据您的编辑,您似乎更喜欢使用颜色名称和直接亮度值。在这种情况下,矢量化函数看起来非常相似:

# 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)))

enter image description here