基于R中的两个对称矩阵创建单个热图

时间:2019-07-09 18:05:37

标签: r matrix heatmap

假设我有两个对称矩阵:

library(Matrix)
set.seed(123)

s1<-forceSymmetric(matrix(round(rnorm(25),2),5))
colnames(s1)<-LETTERS[1:5]
rownames(s1)<-LETTERS[6:10]
diag(s1)<-1

s2<-forceSymmetric(matrix(round(rbinom(25,25,0.3),2),5))
colnames(s2)<-LETTERS[1:5]
rownames(s2)<-LETTERS[6:10]
diag(s2)<-1

s1
# 5 x 5 Matrix of class "dsyMatrix"
# A     B     C     D     E
# F  1.00  1.72  1.22  1.79 -1.07
# G  1.72  1.00  0.36  0.50 -0.22
# H  1.22  0.36  1.00 -1.97 -1.03
# I  1.79  0.50 -1.97  1.00 -0.73
# J -1.07 -0.22 -1.03 -0.73  1.00

s2
# 5 x 5 Matrix of class "dsyMatrix"
# A B  C  D E
# F 1 6  8  7 9
# G 6 1  5  9 8
# H 8 5  1 10 9
# I 7 9 10  1 1
# J 9 8  9  1 1

我想要生成一个单一的热图,其中上对角线及其图例基于矩阵s1,而下对角线及其图例基于矩阵s2。这是我可以找到的类似图片:

enter image description here

1 个答案:

答案 0 :(得分:0)

获取对角线

reverse = s1[,ncol(s1):1]
diag(reverse) = 0
reverse[lower.tri(reverse, diag = FALSE)] <- 0
upper = reverse[,ncol(reverse):1]

降低对角线

reverse1 = s2[,ncol(s2):1]
diag(reverse1) = 0
reverse1[upper.tri(reverse1, diag = FALSE)] <- 0
upper1 = reverse1[,ncol(reverse1):1]

是时候添加它们了。

merged = as.matrix(upper+upper1)
merged
  A    B     C     D    E
F 1.00 1.72  1.22  1.79 0
G 1.72 1.00  0.36  0.00 8
H 1.22 0.36  0.00 10.00 9
I 1.79 0.00 10.00  1.00 1
J 0.00 8.00  9.00  1.00 1

绘制它。

heatmap(merged)

您可以在其他地方找到更好的热图图