原创:黄小仙
很早之前就有小伙伴在后台发消息问有没有R语言画热图的教程,今天小仙终于给安排上了。画了这么多图之后小仙发现,用R画出图并不难,CRAN上有各种R包的资源,同一种图可以有好几种画法。
但是对于注重颜值的朋友来说,想把画出的图形调整成理想的样子,恐怕还是要经历一番折磨人的摸索过程…小仙今天是用pheatmap包来画heatmap,从输入数据到画出图可能只需要几分钟,但是后续的调整折腾了几个小时…
Step1. 绘图数据的准备
首先还是要把你想要绘图的数据调整成R语言可以识别的格式, 在excel中保存成csv。
数据的格式如下图:
Step2. 绘图数据的读取
data <- read.csv(“your file path”, header = T)
Step3.绘图所需package的调用
library(pheatmap) ## 调用之前先安装install.packages("pheatmap")
Step4.绘图
df <- data[,-c(11,12)]
bk <- c(seq(-3, 2,by = 0.01))
pheatmap(df,
cluster_cols = F, cluster_rows = F, scale = "none",
treeheight_col = 0, treeheight_row = 0,
display_numbers = F,
border_color = "black",
color = colorRampPalette(c("blue","white", "red"))(length(bk)))
调整行标签
得到上图之后,小仙发现行名是"1", "2", "3"... ,并不是想要的"Group 1","Group 2", "Group 3"...
原来需要将df的rownames重新赋值一下
rownames(df) <- data$Group
rownames(df)
pheatmap(df,
cluster_cols = F, cluster_rows = F, scale = "none",
treeheight_col = 0, treeheight_row = 0,
display_numbers = F,
border_color = "black",
color = colorRampPalette(c("blue","white", "red"))(length(bk)))
添加行注释
很多时候数据不只一列标签,在画热图的时候除了行名或者列名之外,还要添加注释标签
annotation_row = data.frame(Class = factor(data$Class))
rownames(annotation_row) <- data$Group
pheatmap(df,
cluster_cols = F, cluster_rows = F, scale = "none",
treeheight_col = 0, treeheight_row = 0,
annotation_legend = T,
display_numbers = F,
annotation_row = annotation_row,
border_color = "black",
color = colorRampPalette(c("blue","white", "red"))(length(bk)))
调整热图色块和行注释的颜色
mycolors <- c("#66C2A5","#FC8D62","#E78AC3")
names(mycolors) <- unique(annotation_row$Class)
mycolors <- list(Class = mycolors)
pheatmap(df,
cluster_cols = F, cluster_rows = F, scale = "none",
treeheight_col = 0, treeheight_row = 0,
annotation_legend = T,
display_numbers = F,
annotation_row = annotation_row,
annotation_colors = mycolors,
border_color = "black",
color = colorRampPalette(c("navy", "white", "firebrick3"))(length(bk)))
采用默认颜色
如果希望使用pheatmap包默认的色块颜色,只要将以下的语句删掉就可以。
color = colorRampPalette(c("navy", "white", "firebrick3"))(length(bk))