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

时间:2019-09-24 19:35:14

标签: r ggplot2 colors r-corrplot

我有一个数据集,其最低相关系数为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"

我的图也不会生成。

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

1 个答案:

答案 0 :(得分:1)

我使用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))

enter image description here

颜色的默认范围是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)

enter image description here

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

相关问题