Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
365 views
in Technique[技术] by (71.8m points)

r - assign colors to a range of values

A quick question,

I have a vector with numbers, e.g:

values <- c(0.104654225, 0.001781299, 0.343747296, 0.139326617, 0.375521201, 0.101218053)

and I want to assign a gradient scale to this vector, I know that I can do it with

gray(values/(max(values))

but I would like to use a blue colour scale, for example using colorRampPalette or something similar,

Thanks

I've noticed that there are several questions with similar topics but they map intervals and I would like to map colours to numeric values

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Edit: I now think using colorRampPalette() makes this a bit easier than does colorRamp().

## Use n equally spaced breaks to assign each value to n-1 equal sized bins 
ii <- cut(values, breaks = seq(min(values), max(values), len = 100), 
          include.lowest = TRUE)
## Use bin indices, ii, to select color from vector of n-1 equally spaced colors
colors <- colorRampPalette(c("lightblue", "blue"))(99)[ii]

## This call then also produces the plot below
image(seq_along(values), 1, as.matrix(seq_along(values)), col = colors,
      axes = F)

Among base R functions, colorRamp() is what you are looking for. As dg99 notes, it returns a function that maps values in the range [0,1] to a range of colors.

Unfortunately, it returns a matrix of RGB values, which is not directly usable by most of R's plotting functions. Most of those functions take a col= argument which "wants" sRGB values expressed as hex values in strings that look like "#E4E4FF" or "#9F9FFF". To get those you'll need to apply the rgb() function to the matrix returned by colorRamp(). Here's an example:

f <- colorRamp(c("white", "blue"))
(colors <- rgb(f(values)/255))
# [1] "#E4E4FF" "#FFFFFF" "#A7A7FF" "#DBDBFF" "#9F9FFF" "#E5E5FF"

In practice, you'll probably want to play around with both the color scale and the scaling of your values.

## Scale your values to range between 0 and 1
rr <- range(values)
svals <- (values-rr[1])/diff(rr)
# [1] 0.2752527 0.0000000 0.9149839 0.3680242 1.0000000 0.2660587

## Play around with ends of the color range
f <- colorRamp(c("lightblue", "blue"))
colors <- rgb(f(svals)/255)

## Check that it works
image(seq_along(svals), 1, as.matrix(seq_along(svals)), col=colors,
      axes=FALSE, xlab="", ylab="")

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...