我想将变量的值表示为 R 中散点中的点的颜色。
x <- rnorm(100) + 5
y <- rnorm(100) + 5
plot(x, y)
在这里,我想使用一个变量作为着色的输入。但如果我尝试
plot(x, y, col = x)
我得到了一些奇怪的东西,可能很明显。现在我可以像这样得到我想要的东西:
x_norm = (x - min(x)) / (max(x) - min(x))
col_fun <- colorRamp(c("blue", "red"))
rgb_cols <- col_fun(x_norm)
cols <- rgb(rgb_cols, maxColorValue = 256)
plot(x, y, col = cols)
但这似乎有点复杂,并且要使其与 NA 或 NaN 值一起使用(例如将它们设置为黑色)并不那么容易。为我。有没有一种我忽略的简单方法可以做到这一点?
你应该使用cut http://stat.ethz.ch/R-manual/R-patched/library/base/html/cut.html将 x 划分为区间并且colorRampPalette
用于创建固定大小的调色板:
x <- rnorm(100) + 5
y <- rnorm(100) + 5
maxColorValue <- 100
palette <- colorRampPalette(c("blue","red"))(maxColorValue)
plot(x, y, col = palette[cut(x, maxColorValue)])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)