colorRamp返回0

问题描述:

我想要绘制线条和色彩基于该连接的概率就行。给定一个概率向量,我使用:colorRamp返回0

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

颜色是rgb值的nx3矩阵。然而,colfunc经常会返回一个0值,所以当我尝试使用这些颜色来绘制,R抱怨

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

有没有在我定义我的色彩功能的方法错误?

我有点困惑什么你试图做...的col2rgb函数返回RGB值,所以如果你已经拥有这些,那么你想要什么?

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

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

你的功能工作正常,我想,但它不返回你可以用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提供有关制作可重复问题的提示。