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?