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="")
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…