I would like to represent the value of a variable as the color of a dot in a spread in R.
x <- rnorm(100) + 5
y <- rnorm(100) + 5
plot(x, y)
Here I would like to use a variable as input for coloring. But if I try
plot(x, y, col = x)
I get something strange, perhaps obvious. Now I can get what I want:
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 this seems a bit complicated, and getting it to work with NA or NaN values, for example, giving them black, is not so simple. For me. Is there an easy way to do this that I am missing?
source
share