arielle
arielle

Reputation: 945

R: Create a color vector for specific values from a range

I want to create a vector of colors to then apply it to a barplot. I have created a color range:

color.function <- colorRampPalette(c("blue", "white", "red"))

And then I would like to get the specific colors for specific values contained in a range. For example, let's say that I want the color range to span -10 to 10. Then I want to get the colors for -7, -4.5 and 2 (for example).

How could I do that? I have tried this:

col.seq <- seq(-10, 10, 0.1) 
cuts <- cut(c(-7,-4.5,2), breaks = length(col.seq)) 
colors <- colorRampPalette(c("blue", "white", "red"))(length(col.seq)) 
levels(colors) <- cuts 
colors

but it seems to just give a color per break on my palette.

Any help is appreciated!

Upvotes: 2

Views: 1780

Answers (1)

Bulat
Bulat

Reputation: 6969

To get correct colour for you numeric value you need to find it's idex in the sequence vector you started with.

You can get it with rounding and which:

color.function <- colorRampPalette(c("blue", "white", "red"))

col.seq <- round(seq(-10, 10, 0.1), 1)
colors <- colorRampPalette(c("blue", "white", "red"))(length(col.seq)) 

x <- 6.5323
x.map <- round(x, 1)
x.index <- which(col.seq == x.map)
colors[x.index]
# [1] "#FF5959" 

x <- 1.7323
x.map <- round(x, 1)
x.index <- which(col.seq == x.map)
colors[x.index]
# [1] "#FFD3D3"

Upvotes: 1

Related Questions