R语言学习指南(7) 再探相关性热图

上一节介绍了组内相关性热图的绘制,这一节来介绍组间相关性热图,即由2组数据之间的相关性,废话不多说直接看代码
喜欢可以关注公众号R语言数据分析指南,先行拜谢了

library(pacman)
pacman::p_load(tidyverse,psych,reshape,ggtree,aplot)
table1 <- mtcars[,1:6]
table2 <- mtcars[,7:11]

注:需保证table1与table2行名一致

corr.test计算相关性与p值
pp <- corr.test(table1,table2,method="pearson",adjust = "fdr")
抽提出相关性系数与P值
cor <- pp$r 
pvalue <- pp$p
定义一个函数将p值转化为*
myfun <- function(pval) {
  stars = ""
  if(pval <= 0.001)
    stars = "***"
  if(pval > 0.001 & pval <= 0.01)
    stars = "**"
  if(pval > 0.01 & pval <= 0.05)
    stars = "*"
  if(pval > 0.05 & pval <= 0.1)
    stars = ""
  stars
}
整理数据格式用于ggplot2绘图
heatmap <- melt(cor) %>% rename(replace=c("X1"="sample","X2"="gene",
                               "value"="cor")) %>%
  mutate(pvalue=melt(pvalue)[,3]) %>%
  mutate(signif = sapply(pvalue, function(x) myfun(x)))

write.table (heatmap,file ="heatmap.xls", sep ="\t", row.names = F)  
根据相关性系数矩阵,用ggtree绘制行聚类与列聚类树
phr <- hclust(dist(cor)) %>% 
  ggtree(layout="rectangular", branch.length="none")
phc <- hclust(dist(t(cor))) %>% ggtree() + layout_dendrogram()
ggplot2绘制热图
pp <- ggplot(heatmap,aes(gene,sample,fill=cor)) + 
 geom_tile()+theme_minimal()+
 scale_fill_viridis_c(option ="plasma",limits=c(-0.8,0.8),
 breaks=c(-0.8,-0.4,0,0.4,0.8))+
 geom_text(aes(label=signif),size=8,color="white")+
 scale_y_discrete(position="right")+xlab(NULL) + ylab(NULL)+
 theme(axis.text.x=element_text(angle = 0,hjust=0.5,vjust=0.5,
 family = "Times",face = "plain",colour = "black",size=12),
 axis.text.y=element_text(family= "Times",
 face = "plain",colour = "black",size=12),
 legend.text=element_text(face="plain",family = "Times",
 colour = "black",size = 12))+
 guides(fill = guide_colorbar(direction = "vertical",reverse = F, 
 barwidth = unit(.5, "cm"),
 barheight = unit(15, "cm")))+labs(fill= "")
aplot包将聚类树与热图拼接
pp %>% insert_left(phr, width=.2) %>%
  insert_top(phc, height=.1)

你可能感兴趣的:(R语言学习指南(7) 再探相关性热图)