R use list of values as color scale

大城市里の小女人 提交于 2019-12-06 03:55:36

问题


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)

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?


回答1:


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)])



回答2:


You could work with the predefined grayscale colors gray0, ..., gray99 like this:

x <- rnorm(100) + 5
y <- rnorm(100) + 5
x.renormed <- floor(100*((x-min(x))/(diff(range(x))+1e-2)))
colors.grayscale <- paste("gray",x.renormed,sep="")
plot(x, y, col=colors.grayscale, bg=colors.grayscale,pch=21)

Result:



来源:https://stackoverflow.com/questions/14885107/r-use-list-of-values-as-color-scale

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!