R use list of values as color scale

2020-07-13 11:53发布

问题:

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: