矩阵中基于其值的颜色数字

问题描述 投票:0回答:1

我有一个 2 x 2 矩阵,我想根据数字的值对它们进行着色(假设我有 0-20 的数字,我想将 0-2=蓝色;2-4=天蓝色... 12 -14=黄色,18-20=红色,等等)。在 Excel 中,我只能通过条件格式选项获得 3 种颜色(见图)。任何人都知道我是否可以在另一个程序(最好是 R)中拥有更多颜色。谢谢!

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

snapshot of my excel spreadsheet with the 3 colors based on the values of the numbers

r colors numbers
1个回答
2
投票

这是一个解决方案,希望对你有帮助

# 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])) 
    }
}

Numbers coloured by value

© www.soinside.com 2019 - 2024. All rights reserved.