首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >矩阵中的颜色编号基于它们的值

矩阵中的颜色编号基于它们的值
EN

Stack Overflow用户
提问于 2015-03-03 02:34:29
回答 1查看 1.6K关注 0票数 1

我有一个2 x 2的矩阵,我想根据它们的值给数字上色(假设我有0-20的数字,我想给0-2=蓝色;2-4=天蓝色...12-14=黄色,18-20=红色,依此类推。在Excel中,使用条件格式选项时,我只能使用3种颜色(见下图)。谁知道我是否可以在另一个程序中有更多的颜色(最好是R)。谢谢!

注:请注意,我不需要热图或等高线图本身,因为我对数字的精确值感兴趣。

EN

回答 1

Stack Overflow用户

发布于 2015-03-04 00:19:09

这里有一个解决方案,我希望它能有所帮助。

代码语言:javascript
复制
# 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])) 
    }
}

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28816962

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档