Reputation: 717
I am trying to design a color palette with gradient colors matching values of a numeric variable with R.
I have a vector of values similar to this one. There are negative values, repeating values and missing values.
vec <- c(-1.17, -1.12, 0, 0.01, 0.01, NA, 0.01, -1.17, 1.2, 1.21, 1.35, 1.35, NA, NA)
I am designing the color palette with gradient colors as follows:
colnum <- seq(-1.5, 1.5, 0.01) # to define range of values
library(colorspace)
color <- diverge_hcl(length(colnum))[rank(colnum)] # the color pallette going from blue to red
Now, I am really stuck at the last step. How to extract a matrix where I know which value is assigned to which color?
Here is what I am trying:
values <- data.frame(unique(vec))
colnames(values) <- "colnum"
colpal <- data.frame(colnum, color)
colpal2 <- merge(values, colpal, by="colnum", all.x=TRUE)
colpal2
colnum color
1 -1.17 #6270AF
2 -1.12 #6B77B2
3 0.00 #E2E2E2
4 0.01 <NA>
5 1.20 <NA>
6 1.21 #AA5367
7 1.35 #9D3752
8 NA <NA>
Why am I not getting the color values for 0.01 and 1.20 when they are among the unique values?
unique(vec)
[1] -1.17 -1.12 0.00 0.01 NA 1.20 1.21 1.35
Edit: I also just tried this option and I get the same result.
colpal[colpal$colnum %in% unique(vec), ]
colnum color
34 -1.17 #6270AF
39 -1.12 #6B77B2
151 0.00 #E2E2E2
272 1.21 #AA5367
286 1.35 #9D3752
Can someone explain me what I am doing wrong? Thanks so much!
Upvotes: 1
Views: 64
Reputation: 10362
The solution is a simple as.character
.
colpal[colpal$colnum %in% as.character(unique(vec)), ]
Upvotes: 1