如何将矢量值与R中颜色渐变的颜色相匹配?

时间:2011-06-12 06:36:01

标签: r vector transform

这在R中可能是一件微不足道的事情,但我找不到任何内置函数来做到这一点:

如果给定颜色渐变,如何将值向量(比如数值)转换为颜色向量。

1 个答案:

答案 0 :(得分:7)

上述评论中的想法可以通过seq()cut()来实现。第一步是在数据范围内创建相等的间隔区间

brks <- with(mtcars, seq(min(mpg), max(mpg), length.out = 65))

我们现在将每个观察结果分配给由中断brks

形成的一个区间
grps <- with(mtcars, cut(mpg, breaks = brks, include.lowest = TRUE))

grps是指示数据中每个观察分配到哪个bin的因子

> head(grps)
[1] (20.7,21]   (20.7,21]   (22.5,22.9] (21,21.4]   (18.5,18.8]
[6] (17.7,18.1]
64 Levels: [10.4,10.8] (10.8,11.1] (11.1,11.5] ... (33.5,33.9]

由于grps在内部存储为整数1:nlevels(grps)),我们可以使用此整数来索引颜色渐变:

> terrain.colors(64)[grps]
 [1] "#CADF00FF" "#CADF00FF" "#E6D90EFF" "#D3E100FF" "#96D300FF"
 [6] "#85CF00FF" "#3CBA00FF" "#E8C133FF" "#E6D90EFF" "#9ED500FF"
[11] "#85CF00FF" "#67C700FF" "#76CB00FF" "#51C000FF" "#00A600FF"
[16] "#00A600FF" "#43BC00FF" "#F1D6D3FF" "#EFBEACFF" "#F2F2F2FF"
[21] "#DCE300FF" "#51C000FF" "#51C000FF" "#29B400FF" "#9ED500FF"
[26] "#EBB16EFF" "#EAB550FF" "#EFBEACFF" "#58C300FF" "#AFD900FF"
[31] "#4ABE00FF" "#D3E100FF"

另一种方法可能是使用colourRamp(),它返回一个插入一组提供的颜色的函数。生成的函数采用覆盖颜色渐变范围的[0,1]范围内的值。首先,我们生成一个颜色渐变功能,在红色和蓝色之间进行插值:

FUN <- colorRamp(c("red","blue"))

然后我们获取输入数据并将其打开到[0,1]间隔:

MPG <- with(mtcars, (mpg - min(mpg)) / diff(range(mpg)))

然后我们使用FUN()生成颜色:

> cols <- FUN(MPG)
> head(cols)
         [,1]      [,2] [,3]
[1,] 139.9787 115.02128    0
[2,] 139.9787 115.02128    0
[3,] 120.4468 134.55319    0
[4,] 135.6383 119.36170    0
[5,] 164.9362  90.06383    0
[6,] 171.4468  83.55319    0

FUN()返回的对象是红色,绿色和蓝色通道的值矩阵。要将这些转换为R可以使用的十六进制代码,我们使用rgb()函数:

> rgb(cols, maxColorValue=256)
 [1] "#8B7300" "#8B7300" "#788600" "#877700" "#A45A00" "#AB5300"
 [7] "#D42A00" "#679700" "#788600" "#9F5F00" "#AE5000" "#BD4100"
[13] "#B34B00" "#CA3400" "#FE0000" "#FE0000" "#D02E00" "#10EE00"
[19] "#26D800" "#00FE00" "#867800" "#C73700" "#CA3400" "#DF1F00"
[25] "#9F5F00" "#47B700" "#55A900" "#26D800" "#C43A00" "#996500"
[31] "#CC3200" "#877700"