R語言繪製熱圖——pheatmap
阿新 • • 發佈:2019-01-22
(網易雲課堂,騰訊課堂生物資訊講師,高階生物資訊工程師)
pheatmap簡介: Pretty Heatmaps——Implementation of heatmaps that offers more control over dimensions and appearance.
#預設引數下是對行列均進行聚類(可設定cluster_row = FALSE, cluster_col = FALSE不進行行列的聚類;如果進行聚類了,還可以通過設定treeheight_row=0, treeheight_col=0不顯示dendrogram),矩陣沒有進行標準化(標準化引數為scale,可選"none", "row", "column"),熱圖的每個小塊之間以灰色隔開(引數border_color,如果不想要border可以設定為NA,當然也可以設定成其它顏色),legend顯示在右上方(可設定legend = FALSE不顯示legend);熱圖的顏色可利用引數color調整;library(pheatmap) #建立資料集test測試矩陣 test = matrix(rnorm(200), 20, 10) test[1:10, seq(1, 10, 2)] = test[1:10, seq(1, 10, 2)] + 3 test[11:20, seq(2, 10, 2)] = test[11:20, seq(2, 10, 2)] + 2 test[15:20, seq(2, 10, 2)] = test[15:20, seq(2, 10, 2)] + 4 colnames(test) = paste("Test", 1:10, sep = "") rownames(test) = paste("Gene", 1:20, sep = "") # 用pheatmap函式畫熱圖 pheatmap(test)
pheatmap(test, cluster_row = FALSE, legend_breaks = -1:4, legend_labels = c("0", |
"1e-4", "1e-3", "1e-2", "1e-1", "1"))#可自己設定圖例#可設定引數display_numbers將數值顯示在熱圖的格子中,可通過number_format設定數值的格式,較常用的有"%.2f"(保留小數點後兩位),"%.1e"(科學計數法顯示,保留小數點後一位),number_color設定顯示內容的顏色:
pheatmap(test, display_numbers = TRUE, number_format = "%.2f", number_color="purple") #"%.2f"表示保留小數點後兩位
# 在熱圖格子裡展示文字 pheatmap(test, display_numbers = TRUE) pheatmap(test, display_numbers = TRUE, number_format = "\%.1e") pheatmap(test, display_numbers = matrix(ifelse(test > 5, "*", ""), nrow(test)))#還可以自己設定要顯示的內容;
#pheatmap引數設定改變每個格子的大小
pheatmap(test, cellwidth = 15, cellheight = 12, main = "Example heatmap", fontsize = 8, filename = "test.pdf") #main可設定熱圖的標題,fontsize設定字型大小,filename可直接將熱圖存出,支援格式png, pdf, tiff, bmp, jpeg,並且可以通過width, height設定圖片的大小;
#pheatmap還可以顯示行或列的分組資訊,支援多種分組;
annotation_col = data.frame(CellType = factor(rep(c("CT1", "CT2"), 5)), Time = 1:5)
rownames(annotation_col) = paste("Test", 1:10, sep = "")
annotation_row = data.frame(GeneClass = factor(rep(c("Path1", "Path2", "Path3"), c(10, 4, 6))))
rownames(annotation_row) = paste("Gene", 1:20, sep = "")
pheatmap(test, annotation_col = annotation_col, annotation_row = annotation_row)
#設定各個分組的顏色
ann_colors = list(Time = c("white", "firebrick"), #連續數值型分組可設定成漸變
CellType = c(CT1 = "#1B9E77", CT2 = "#D95F02"),
GeneClass = c(Path1 = "#7570B3", Path2 = "#E7298A", Path3 = "#66A61E"))
pheatmap(test, annotation_col = annotation_col, annotation_row = annotation_row,
annotation_colors = ann_colors)
#pheatmap還能夠根據特定的條件將熱圖分隔開;
# cutree_rows, cutree_cols:根據行列的聚類數將熱圖分隔開;
pheatmap(test,cutree_rows=3,cutree_cols=2)
#還可以自己設定各個分組的顏色
ann_colors = list(Time = c("white", "firebrick"), #連續數值型分組可設定成漸變
CellType = c(CT1 = "#1B9E77", CT2 = "#D95F02"),
GeneClass = c(Path1 = "#7570B3", Path2 = "#E7298A", Path3 = "#66A61E"))
pheatmap(test, annotation_col = annotation_col, annotation_row = annotation_row,
annotation_colors = ann_colors)
#還可以利用gaps_row, gaps_col自己設定要分隔開的位置
pheatmap(test, annotation_col = annotation_col, cluster_rows = FALSE, gaps_row = c(10, 14),
cutree_col = 2)