我有这个融化的矩阵,我想绘制为热图,相关系数在下面的矩阵中,P值在上面的三角形中
> melted_corfinal
Var1 Var2 value
1 iHS iHS 1.00
2 nSL iHS 0.89
3 XP-EHH iHS 0.01
4 PBS iHS 0.00
5 iHS nSL 0.00
6 nSL nSL 1.00
7 XP-EHH nSL 0.01
8 PBS nSL 0.00
9 iHS XP-EHH 0.00
10 nSL XP-EHH 0.00
11 XP-EHH XP-EHH 1.00
12 PBS XP-EHH 0.18
13 iHS PBS 0.90
14 nSL PBS 0.41
15 XP-EHH PBS 0.00
16 PBS PBS 1.00
但是,我找不到只改变上三角矩阵颜色的方法,同时保持值。我希望它只是白色(背景)。
这是我到目前为止的代码:
p <- ggplot(melted_corfinal, aes(Var2, Var1)) +
geom_tile(aes(fill = value)) +
geom_text(aes(label = round(value, 2))) +
scale_fill_continuous("",limits=c(0, 1), breaks=seq(0,1,by=0.2),low = "#fee8c8", high = "#e34a33") +
theme_light() + theme(legend.position="none",axis.title.x = element_blank(),axis.title.y = element_blank()) +
guides(fill = guide_colorbar(barwidth = 20)) +
ylim(rev(levels(melted_corfinal$Var1))) + xlim(levels(melted_corfinal$Var2))
plot(p)
另外,我仍然希望表格中存在2个小数位,但它们是&#34;舍入&#34;当他们为零。 dput:
structure(list(Var1 = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L,
4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L), .Label = c("iHS", "nSL",
"XP-EHH", "PBS"), class = "factor"), Var2 = structure(c(1L, 1L,
1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L), .Label = c("iHS",
"nSL", "XP-EHH", "PBS"), class = "factor"), value = c(1, 0.89,
0.01, 0, 0, 1, 0.01, 0, 0, 0, 1, 0.18, 0.9, 0.41, 0, 1)), .Names = c("Var1",
"Var2", "value"), row.names = c(NA, -16L), class = "data.frame")
答案 0 :(得分:2)
好的,首先我将您提供的数据转换回常规的未融合矩阵,这样我就可以轻松地将NA设置为上三角形。我用dcast
执行此操作。该矩阵已经是对角线和下三角形的相关性以及上三角形上的p值的组合。
melted_corfinal <- structure(list(Var1 = structure(c(1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L, 1L, 2L, 3L, 4L),
.Label = c("iHS", "nSL", "XP-EHH", "PBS"), class = "factor"),
Var2 = structure(c(1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L),
.Label = c("iHS", "nSL", "XP-EHH", "PBS"), class = "factor"),
value = c(1, 0.89, 0.01, 0, 0, 1, 0.01, 0, 0, 0, 1, 0.18, 0.9, 0.41, 0, 1)),
.Names = c("Var1", "Var2", "value"), row.names = c(NA, -16L), class = "data.frame")
cor_pval <- dcast(melted_corfinal, Var1~Var2)[, -1]
# Set to NA upper triangle excluding diagonal
cor_pval[upper.tri(cor_pval, diag=F)] <- NA
然后我将其融化并添加为melted_corfinal
cor_pval_col <- melt(cor_pval)
melted_corfinal$value2 <- cor_pval_col$value
melted_corfinal
现在我们按照您的情节进行绘制,但对于geom_tile
,我们将value2
与NA一起用于p值。然后,我们在na.value="white"
中设置scale_fill_continuous
。
最后得到2个有效数字的0&#39; s我使用format
p <- ggplot(melted_corfinal, aes(Var2, Var1)) +
geom_tile(aes(fill = value2)) +
scale_fill_continuous("",limits=c(0, 1), breaks=seq(0,1,by=0.2), low = "#fee8c8", high = "#e34a33", na.value = "white") +
geom_text(aes(label = format(value, nsmall=2))) +
theme_light() + theme(legend.position="none",axis.title.x = element_blank(),axis.title.y = element_blank()) +
guides(fill = guide_colorbar(barwidth = 20)) +
ylim(rev(levels(melted_corfinal$Var1))) + xlim(levels(melted_corfinal$Var2))
p