Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R use list of values as color scale

Tags:

plot

r

colors

scale

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)

enter image description here

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?

like image 997
Gijs Avatar asked Feb 14 '13 22:02

Gijs


2 Answers

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)])
like image 163
AndreyAkinshin Avatar answered Oct 10 '22 05:10

AndreyAkinshin


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:

grayscale scatterplot

like image 45
Stephan Kolassa Avatar answered Oct 10 '22 06:10

Stephan Kolassa