我有一个2乘2的矩阵,我想根据它们的值对数字进行着色(比如我的数字从0到20,我想要颜色0-2 =蓝色; 2-4 =天蓝色.. 12-14 =黄色,18-20 =红色等。在Excel中,我只能使用条件格式选项获得3种颜色(参见图)。任何人都知道我是否可以在另一个程序中拥有更多颜色(最好是R)。谢谢!
PS:请注意,我本身不需要热图或等高线图,因为我对数字的确切值感兴趣。
答案 0 :(得分:2)
这是一个解决方案,我希望它有所帮助
# you need this for the colour ramp
library(RColorBrewer)
# setup
rows <- 10
collumns <- 10
# data matrix
zVals <- round(rnorm(rows*collumns), 2)
z <- matrix(zVals, rows, collumns)
# 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, collumns),
axes = F, xlab = "", ylab = "")
# populate it with the data
for(r in 1:rows){
for(c in 1:collumns){
text(c, r, z[c,r], col = findNearestColour(z[c,r]))
}
}