你的功能工作正常,我想,但它不返回你可以用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提供有關製作可重複問題的提示。