本文介绍了R-如何绘制显示显著相关性的热图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很大的热图。我想通过只显示Spearman相关性大于0.5和小于-0.5的变量来更清楚地绘制它。这导致相关矩阵带有空格以实现更大的相关性。因此,热图也有空格。我想要一个热图,它以描述的方式显示相关性(当p.值低于0.05时使用*),但空白处不是白色,而是适当的颜色。
此代码生成一个带有空格的热图,如何将正确的相关性放回提供热图的矩阵中?如何避免热图中出现空格?
library(tidyverse)
library(ggplot2)
library(gplots)
#data.frame
df <- data.frame(var.1 = c('gucci','prada','lacoste','pseudo','gucci','prada','lacoste','pseudo'),var.2 = c('carat.1','carat.1','carat.1','carat.1','carat.2','carat.2','carat.2','carat.2'),spearman = c(-0.5,0.5,-1,0.02,-0.5,0.5,-1,0.02),p.value = c(0.05,0.5,1,0.03,0.05,0.5,1,0.03))
#only spearman greater 0.5 and lower -0.5
df.spe <- df[df$spearman >= 0.5 | df$spearman <= -0.5,]
#heatmap matrix
sub <- df.spe %>% dplyr::select(.,everything(),-starts_with('p.adj.log')) %>% pivot_wider(.,names_from = 'var.1',values_from = 'estimate') %>%
column_to_rownames(.,'var.2') %>% data.matrix(.)
sub2 <- df.spe %>% dplyr::select(.,everything(),-starts_with('estimate')) %>% pivot_wider(.,names_from = 'var.1',values_from = 'p.adj.log') %>%
column_to_rownames(.,'var.2') %>% data.matrix(.)
sub2 <- ifelse(sub2 >= -log10(0.05),'*','')
#heatmap
heatmap.2(sub,cexRow = .35,cexCol = .35,trace = 'none',key.title = 'Spearman correlation',col = my_palette,keysize = .5,key.par = list(cex=.4) ,notecol = 'black',srtCol = 30,cellnote = sub2)
谢谢;)
推荐答案
您没有提供可复制的数据,我不清楚您到底要实现什么目标。
如果我理解正确,您似乎生成了";空格";,但您并不希望这样,而是只想用星号突出显示重要的大小写。
看看我下面的可重现的例子,看看它是否能帮助你实现你想要的东西。
从那里开始,如果您只想保留三角矩阵,而将其余部分清空,则可以将相关矩阵和p值矩阵的lower.tri
(如果您愿意,diag
)设置为NA
,而不是聚集热图的行和列。
library(Hmisc) # for correlations and p-values
library(RColorBrewer) # for color palette
library(gplots)
# define a color palette
my_palette <- colorRampPalette(rev(brewer.pal(n = 7, name = "RdYlBu")))(100)
# generate reproducible matrix to calculate correlations on
set.seed(23)
mat <- matrix(stats::runif(100, 3, 14), nrow = 10, ncol = 10,
dimnames = list(paste0("Brand", 1:10), paste0("Val", 1:10)))
modmat <- sample(1:10, 4)
mat[modmat, 1:5] <- mat[modmat,1:5] + stats::runif(20, 4, 6)
mat[modmat, 6:10] <- 14-mat[modmat, 1:5] # for negative correlation
# calculate spearman-rank correlation
cor.mat <- rcorr(t(mat), type = "spearman")
# only keep comparisons that have some abs. correlation >= .5 (optional)
keep <- rownames(cor.mat$r)[rowSums(abs(cor.mat$r)>=0.5) > 1]
cor.mat <- lapply(cor.mat, function(x) x[keep, keep])
# set diagonal to 1, since it is not interesting and should not be marked
diag(cor.mat$P) <- 1
# plot heatmap and mark cells with abs(r) >= .5 and p < 0.05
heatmap.2(cor.mat$r,
# cexRow = .35, cexCol = .35,
trace = 'none',
key.title = 'Spearman correlation',
# keysize = .5, key.par = list(cex=.4),
notecol = 'black', srtCol = 30,
col = my_palette,
cellnote = ifelse(cor.mat$P < 0.05 & abs(cor.mat$r)>=0.5, "*", ""))
在2021-02-22创建
这篇关于R-如何绘制显示显著相关性的热图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!