我有一个看起来像这样的矩阵
set.seed(1)
X <- matrix(runif(20,-6,6),5)
> X
[,1] [,2] [,3] [,4]
[1,] -2.8138960 4.780676 -3.528305 -0.02760909
[2,] -1.5345132 5.336103 -3.881319 2.61142210
[3,] 0.8742404 1.929574 2.244274 5.90287314
[4,] 4.8984935 1.549369 -1.390755 -1.43957785
[5,] -3.5798168 -5.258565 3.238097 3.32934266
我希望用它中的数字来定义图形的颜色,就像这样。
X[X >= 6] <- "#4575B4"
X[X < 6] <- "#74ADD1"
X[X < 4] <- "#ABD9E9"
X[X < 2] <- "#E0F3F8"
X[X < 0] <- "#FEE090"
X[X < -2] <- "#FDAE61"
X[X < -4] <- "#F46D43"
X[X < -6] <- "#D73027"
但是,我得到以下矩阵
> X
[,1] [,2] [,3] [,4]
[1,] "#FEE090" "#FEE090" "#FEE090" "#FEE090"
[2,] "#FEE090" "#FEE090" "#FEE090" "#FEE090"
[3,] "#FEE090" "#FEE090" "#FEE090" "#FEE090"
[4,] "#FEE090" "#FEE090" "#FEE090" "#FEE090"
[5,] "#FEE090" "#FEE090" "#FEE090" "#FEE090"
如何使用我想要的颜色?提前谢谢!
答案 0 :(得分:2)
试试这个:
XX <- X
XX[X >= 6] <- "#4575B4"
XX[X < 6] <- "#74ADD1"
XX[X < 4] <- "#ABD9E9"
XX[X < 2] <- "#E0F3F8"
XX[X < 0] <- "#FEE090"
XX[X < -2] <- "#FDAE61"
XX[X < -4] <- "#F46D43"
XX[X < -6] <- "#D73027"
XX
[,1] [,2] [,3] [,4]
[1,] "#FDAE61" "#74ADD1" "#FDAE61" "#FEE090"
[2,] "#FEE090" "#74ADD1" "#FDAE61" "#ABD9E9"
[3,] "#E0F3F8" "#E0F3F8" "#ABD9E9" "#74ADD1"
[4,] "#74ADD1" "#E0F3F8" "#FEE090" "#FEE090"
[5,] "#FDAE61" "#F46D43" "#ABD9E9" "#ABD9E9"
答案 1 :(得分:1)
您可以尝试cut
lab <- c("#D73027", "#F46D43", "#FDAE61", "#FEE090", "#E0F3F8",
"#ABD9E9", "#74ADD1", "#4575B4")
X1 <- X
X1[] <- as.character(cut(X, breaks=c(-Inf,
seq(-6, 6, by=2), Inf), labels=lab))
X1
# [,1] [,2] [,3] [,4]
#[1,] "#FDAE61" "#74ADD1" "#FDAE61" "#FEE090"
#[2,] "#FEE090" "#74ADD1" "#FDAE61" "#ABD9E9"
#[3,] "#E0F3F8" "#E0F3F8" "#ABD9E9" "#74ADD1"
#[4,] "#74ADD1" "#E0F3F8" "#FEE090" "#FEE090"
#[5,] "#FDAE61" "#F46D43" "#ABD9E9" "#ABD9E9"