更改相关矩阵配色方案以从指定的颜色标签开始

Changing correlation matrix color scheme to start at specified colorlabel

我有一个数据集,其中最低相关系数为 0.83,最高约为 0.99。我在 R 中使用 "corrplot" 包,并尝试使用 "colorRamps" 包获取色谱。我还希望频谱的最末端从我指定的上限和下限 (0.8, 1) 开始。我几乎到处都看过,但似乎找不到解决方案。我也无法加载我想要的配色方案。

我已成功使用 colorRampPalette,但我仍然无法让色谱的起点和终点在我指定的范围内开始和结束。

这是我尝试过的:

library(corrplot)
library(colorRampPalette)
library(colorRamps)

pal <- colorRamps::matlab.like2


###########Notice my cl.lim is set to 0.8-1################

corrplot(data, method = "number", type="lower", is.corr=FALSE, margin=c(0,0,0,0),col=pal, tl.col='black', cl.lim = c(0.8, 1),tl.cex=0.7, outline=TRUE, title = "9 DAT")

在 运行 "corrplot" 代码行之后,我得到以下内容:

"Warning messages:
1: In text.default(pos.xlabel[, 1], pos.xlabel[, 2], newcolnames, srt = tl.srt,  :
  "margin" is not a graphical parameter
2: In text.default(pos.ylabel[, 1], pos.ylabel[, 2], newrownames, col = tl.col,  :
  "margin" is not a graphical parameter
3: In title(title, ...) : "margin" is not a graphical parameter"

我的图表也没有生成。

非常感谢您的帮助。谢谢大家!

我用ggplot2作图。那么,让我向您展示如何在 ggplot2 中实现您所需要的。让我们先生成一个有效的相关矩阵:

library(ggplot2)
library(tidyr)
library(ggplot2)

set.seed(123)

df <- data.frame(X1 = 1:100,
                 X2 = 0.75*(1:100) + rnorm(100),
                 X3 = 0.25*(1:100) + rnorm(100,sd = 20),
                 X4 = 0.5*(1:100) + rnorm(100,sd = 10))

cm <- round(cor(df), 2)
cm[lower.tri(cm)] <- NA

cm <- as.data.frame(cm) %>% 
  mutate(Var1 = factor(row.names(.), levels=row.names(.))) %>% 
  gather(key = Var2, value = value, -Var1, na.rm = TRUE, factor_key = TRUE)

输出

# Var1 Var2 value
# 1    X1   X1  1.00
# 5    X1   X2  1.00
# 6    X2   X2  1.00
# 9    X1   X3  0.43
# 10   X2   X3  0.43
# 11   X3   X3  1.00
# 13   X1   X4  0.86
# 14   X2   X4  0.85
# 15   X3   X4  0.38
# 16   X4   X4  1.00

现在,假设要使用 ggplot2:

绘制此相关矩阵
ggplot(data = cm) + 
  geom_tile(aes(Var2, Var1, fill = value)) +
  scale_fill_gradientn(colours = rainbow(5))

颜色的默认范围是 range(cm$value),即它跨越目标变量的整个范围。假设要使用 [0.5, 0.9] 的范围。这不能通过简单地更改 limits 变量来实现 - 简单地使用 limits 将导致绘图上出现灰色区域。可以为此使用 oob = scales::squish 参数(阅读它的作用):

ggplot(data = cm) + 
  geom_tile(aes(Var2, Var1, fill = value)) +
  scale_fill_gradientn(colours = rainbow(5), limits = c(0.5, 0.9),
                       oob = scales::squish)

这将确保针对新范围正确调整颜色。