R使用值列表作为色标 [英] R use list of values as color scale

查看:98
本文介绍了R使用值列表作为色标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将变量的值表示为R中的散点中的点的颜色。

I'd like to represent the value of a variable as a color of a dot in a scatter in R.

x <- rnorm(100) + 5
y <- rnorm(100) + 5
plot(x, y)

在这里,我想使用变量作为着色的输入。但是,如果我尝试

Here, I'd like to use a variable as input for the coloring. But if I try

plot(x, y, col = x)

我很奇怪,可能很明显。现在我可以得到我想要的东西:

I get something weird, probably obviously. Now I can get what I want like this:

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值配合使用(例如通过将其设为黑色作为颜色)并非易事。为了我。有一个简单的方法可以让我忽略吗?

But that seems a little elaborate, and to get it working with NA or NaN values, for example by giving them black as color, is not so easy. For me. Is there an easy way to do this that I'm overlooking?

推荐答案

您应使用 cut 表示将x分为间隔和 colorRampPalette 用于创建固定大小的调色板:

You should use cut for devide x into intervals and colorRampPalette for create fixed size palette:

x <- rnorm(100) + 5
y <- rnorm(100) + 5
maxColorValue <- 100
palette <- colorRampPalette(c("blue","red"))(maxColorValue)
plot(x, y, col = palette[cut(x, maxColorValue)])

这篇关于R使用值列表作为色标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆