热图的教程网上一抓一大把,这里使用pheatmap。
另外强力推荐ComplexHeatmap
library(pheatmap)
rt<-read.csv("yourdir/liver_cpm_1_all.csv",header = T,row.names = 1,check.names = F)
rt[1:4,1:4]
GTEX-1192X-1026-SM-5H12P GTEX-11DXY-0526-SM-5EGGQ GTEX-11DXZ-0126-SM-5EGGY GTEX-11EQ9-0526-SM-5A5JZ
ENSG00000227232 9.9633549 5.925740 4.691167 2.484820
ENSG00000237683 5.1900366 5.016777 1.097475 2.165542
ENSG00000225972 0.7387278 3.286251 805.029998 1.513103
ENSG00000225630 45.0813398 623.321412 355.840044 216.512510
group<-read.csv("yourdir/gene_list.csv",header = T,check.names = F)
group[1:4,1:2]
list Group
1 ENSG00000165637 TOP
2 ENSG00000254827 TOP
3 ENSG00000134962 TOP
4 ENSG00000226479 TOP
genes<-as.character(group[,1])
data<-rt[genes,]
annotation_row<-data.frame(Group=factor(group[,2]))#对行(基因名进行分组,TOP,BOTTOM组)
row.names(annotation_row)<-row.names(data)
ann_colors <- list(Group=c( TOP ="aquamarine1",BOTTOM="plum1"))#设置row两组的颜色
pheatmap(log10(data+0.001),annotation_row =annotation_row,annotation_colors = ann_colors,color = colorRampPalette(c("navy", "white", "firebrick3"))(30),cellwidth =1.6, cellheight = 0.05,cluster_rows=F,cluster_cols = T,show_rownames = F,show_colnames = F)#取对数让数值分布更均匀
第二个例子,两组bar,并有分割
Treatment_ann<-data.frame()
Treatment<-c(rep("Treatment1",5),rep("Treatment2",5),rep("Treatment1",5),rep("Treatment2",5))
Species<-c(rep("Group1",10),rep("Group2",10))
Treatment_ann<-data.frame(Treatment,Species)
row.names(Treatment_ann)<-colnames(Treatment)
Treatment_ann_colors <- list(Treatment=c( Treatment1 ="#0A5EB9",Treatment2="#EBB208"),Species=c( Group1 ="aquamarine1",Group2="plum1"))
Humanized_Treatment_filnename<-paste0("~/data_dir/heatmap_files/Humanized_Treatment_heatmap_plot.pdf")
pdf(file =Humanized_Treatment_filnename,width = 7,height = 7 )
pheatmap(Treatment,annotation_col =Treatment_ann,
annotation_colors = Treatment_ann_colors,color = colorRampPalette(c("navy", "white", "firebrick3"))(30),
cellwidth =12, cellheight =0.5 ,cluster_rows=T,cluster_cols = F,show_rownames = F,show_colnames = F,gaps_col = 10)
dev.off()
#调整颜色
#https://stackoverflow.com/questions/32545256/define-specific-value-colouring-with-pheatmap-in-r
makeColorRampPalette <- function(colors, cutoff.fraction, num.colors.in.palette)
{
stopifnot(length(colors) == 4)
ramp1 <- colorRampPalette(colors[1:2])(num.colors.in.palette * cutoff.fraction)
ramp2 <- colorRampPalette(colors[3:4])(num.colors.in.palette * (1 - cutoff.fraction))
return(c(ramp1, ramp2))
}
cutoff.distance <- 3
cols <- makeColorRampPalette(c("navy", "white", # distances 0 to 3 colored from white to red
"white", "firebrick3"), # distances 3 to max(distmat) colored from green to black
0,
100)
pheatmap(new_rt,annotation_row =row_ann,annotation_col =col_ann,
#gaps_col = 8,
annotation_colors = ann_colors,color = cols,border_color="black",
cellwidth =14, cellheight =14 ,cluster_rows=F,cluster_cols = F,show_rownames = F,show_colnames = F,
)