Reputation: 73
I have a 2 by 2 matrix and I would like to color the numbers based on their values (say I have numbers from 0-20 and I want to color 0-2=blue; 2-4=sky blue... 12-14=yellow, 18-20=red, etc.). In Excel I was only able to have 3 colors with the Conditional Formatting option (see the figure). Anyone knows if I can have more colors in another program (preferably R). Thanks!
PS: Please note, I do not need a heatmap or contour plot per se, because I am interested in the exact values of the numbers.
Upvotes: 2
Views: 1944
Reputation: 1370
Here is a solution, I hope it helps
# you need this for the colour ramp
library(RColorBrewer)
# setup
rows <- 10
columns <- 10
# data matrix
zVals <- round(rnorm(rows*columns), 2)
z <- matrix(zVals, rows, columns)
# pick the number of colours (granularity of colour scale)
nColors <- 100
# create the colour pallete
cols <-colorRampPalette(colors=c("blue", "grey", "red"))(nColors)
# get a zScale for the colours
zScale <- seq(min(z), max(z), length.out = nColors)
# function that returns the nearest colour given a value of z
findNearestColour <- function(x) {
colorIndex <- which(abs(zScale - x) == min(abs(zScale - x)))
return(cols[colorIndex])
}
# empty plot
plot(1, 1, type = "n", xlim = c(1, rows), ylim = c(1, columns),
axes = F, xlab = "", ylab = "")
# populate it with the data
for(r in 1:rows) {
for(c in 1:columns) {
text(c, r, z[c,r], col = findNearestColour(z[c,r]))
}
}
Upvotes: 2