美文网首页R语言做图
九. R语言作图--pheatmap(热图)

九. R语言作图--pheatmap(热图)

作者: 小飞虎 | 来源:发表于2021-09-16 11:37 被阅读0次

1. 热图及分组

library(pheatmap) #加载库
test=read.table('abc.txt', header = T, sep = ',') #导入数据
row.names(test)=test[,1] #设定行名
test=scale(test[,-1]) #数据去掉第一列并标准化
annotation_col = data.frame(
  CellType = factor(rep(c("CT1", "CT2", "CT3"), 3)), 
  Time = c(1,1,1,2,2,2,3,3,3)
) #列分组
rownames(annotation_col) = colnames(test)#指定annotation_col行名

annotation_row = data.frame(
  GeneClass = factor(rep(c("Path1", "Path2", "Path3"), c(8, 8, 8)))
)#行分组
rownames(annotation_row) = rownames(test)#指定annotation_row行名
ann_colors = list(
  Time = c("white", "firebrick"),
  CellType = c(CT1 = "#1B9E77", CT2 = "#D95F02", CT3 = "#7570b3"),
  GeneClass = c(Path1 = "#7570B3", Path2 = "#E7298A", Path3 = "#66A61E")
)#设置分组颜色

pheatmap(test, 
         annotation_col = annotation_col, 
         annotation_row = annotation_row,
         display_numbers = matrix(ifelse(test > 3, "*", ""), nrow(test)),#标注*
         gaps_row = c(8, 16),#设置行间隔
         cutree_cols = 3,#设置列间隔
         show_rownames = T,
         cluster_rows = F,#设置行不聚类
         annotation_colors = ann_colors[2],
         labels_row =paste("gene", 1:24, sep = ""),#重命名
         labels_col =paste("sample", 1:9, sep = ""),#重命名
         )#画图
pheatmap.png

2. 热图聚类和排序

绘制热图的时候我们会遇到这样的问题,我们有一组数据(特别是数据比较多的时候),绘制热图后分别对行和列进行聚类,然后我们想导出聚类后的表达矩阵,该如何实现?

library(pheatmap)
test=read.table('abc.txt', header = T, sep = '\t')
row.names(test)=test[,1]
test=test[,-1]
pheatmap(test,cluster_rows = F, cluster_cols = F,show_colnames = F,show_rownames = F) #Fig01 原始表达矩阵直接展示
pheatmap(test,show_colnames = F,show_rownames = F) #Fig02 对原始表达矩阵的行和列分别聚类
#pheatmap(test, kmeans_k =4)
#pheatmap(test,  clustering_distance_rows = "correlation")#scale = "row",
#pheatmap(test, color = colorRampPalette(c("navy", "white", "firebrick3"))(50))
#pheatmap(test, cluster_row = T,fontsize_row = 6, fontsize_col = 0.2)
p<-pheatmap(test, cluster_row = T,cluster_col = T,show_colnames = F,show_rownames = F,fontsize_row = 4, fontsize_col = 0.2)
p
gn=rownames(test)[p$tree_row[["order"]]]
sn=colnames(test)[p$tree_col[["order"]]]
new_test=test[gn,sn]
new_test #Fig03 对原始表达矩阵的行和列分别聚类后的矩阵
p<-pheatmap(new_test, cluster_rows = F, cluster_cols = F, show_colnames = F,show_rownames = F, fontsize_row = 4, fontsize_col = 0.2)
write.csv(new_test,file = "4_new.csv") #输出聚类后的矩阵
Fig01.png
Fig02.png
Fig03.png

相关文章

网友评论

    本文标题:九. R语言作图--pheatmap(热图)

    本文链接:https://www.haomeiwen.com/subject/rgxlgltx.html