colorRamp返回0

时间:2014-12-05 21:44:40

标签: r colors color-palette

我正在尝试根据连接的概率绘制线条并为线条着色。给定一个概率向量,我使用:

colfunc <- colorRamp(c("white", "red"))
colors <- colfunc(probs)
然后,

颜色是rgb值的nx3矩阵。但是,colfunc经常返回0值,因此当我尝试使用这些颜色绘图时,R抱怨

Error in col2rgb(colors) : numerical color values must be positive

我定义颜色功能的方式是否有错误?

2 个答案:

答案 0 :(得分:1)

我认为你的功能运行正常,但它不能返回plot可以使用的颜色,因为plot想要一种颜色,而不是矩阵中的RGB值。

可能有更好的方法,但你可以简单地转换矩阵:

probs <- runif(10)
colors <- colfunc(probs)
my_col = apply(colors, MARGIN = 1,  function(x) rgb(x[1]/255, x[2]/255, x[3]/255))

plot(1:10, 1:10, col = my_col) # should work fine

或者你可以包装你的功能

better_colfunc <- function(x, ramp = colorRamp(c("white", "red"))) {
   colors <- ramp(x)
   colors = apply(colors, MARGIN = 1,  function(x) rgb(x[1]/255, x[2]/255, x[3]/255))
   return(colors)
}

plot(1:10, 1:10, col = better_colfunc(probs, ramp = colfunc))

至于“colfunc经常返回一个0值”和其他问题,你需要共享一些数据(你的probs看起来是什么样的?)以及实际的绘图代码。 See here有关制作可重现问题的提示。

答案 1 :(得分:-1)

我有点困惑你想要做什么... col2rgb函数返回rgb值,所以如果你已经有了那些你想要的是什么?

或者如果你想要rgb,为什么不使用:

col2rgb(c("white", "red"))