丁香五月天婷婷久久婷婷色综合91|国产传媒自偷自拍|久久影院亚洲精品|国产欧美VA天堂国产美女自慰视屏|免费黄色av网站|婷婷丁香五月激情四射|日韩AV一区二区中文字幕在线观看|亚洲欧美日本性爱|日日噜噜噜夜夜噜噜噜|中文Av日韩一区二区

您正在使用IE低版瀏覽器,為了您的雷峰網(wǎng)賬號安全和更好的產(chǎn)品體驗,強(qiáng)烈建議使用更快更安全的瀏覽器
此為臨時鏈接,僅用于文章預(yù)覽,將在時失效
人工智能開發(fā)者 正文
發(fā)私信給AI研習(xí)社
發(fā)送

0

一文詳解如何用 R 語言繪制熱圖

本文作者: AI研習(xí)社 2017-06-15 15:30
導(dǎo)語:關(guān)于 R 語言繪制熱圖,你需要了解這些。

雷鋒網(wǎng)按:作為目前最常見的一種可視化手段,熱圖因其豐富的色彩變化和生動飽滿的信息表達(dá)被廣泛應(yīng)用于各種大數(shù)據(jù)分析場景。同時,專用于大數(shù)據(jù)統(tǒng)計分析、繪圖和可視化等場景的 R 語言,在可視化方面也提供了一系列功能強(qiáng)大、覆蓋全面的函數(shù)庫和工具包。因此,對相關(guān)從業(yè)者而言,用 R 語言繪制熱圖就成了一項最通用的必備技能。本文將以 R 語言為基礎(chǔ),詳細(xì)介紹熱圖繪制中遇到的各種問題和注意事項。原文作者 taoyan,原載于作者個人博客,雷鋒網(wǎng)已獲授權(quán)。

簡介

本文將繪制靜態(tài)與交互式熱圖,需要使用到以下R包和函數(shù):

● heatmap():用于繪制簡單熱圖的函數(shù)

● heatmap.2():繪制增強(qiáng)熱圖的函數(shù)

● d3heatmap:用于繪制交互式熱圖的R包

● ComplexHeatmap:用于繪制、注釋和排列復(fù)雜熱圖的R&bioconductor包(非常適用于基因組數(shù)據(jù)分析)

數(shù)據(jù)準(zhǔn)備

使用R內(nèi)置數(shù)據(jù)集 mtcars

df <- as.matrix((scale(mtcars))) #歸一化、矩陣化

使用基本函數(shù)繪制簡單簡單熱圖

主要是函數(shù) heatmap(x, scale="row")

● x: 數(shù)據(jù)矩陣

● scale:表示不同方向,可選值有:row, columa, none

● Default plotheatmap(df, scale = "none")

一文詳解如何用 R 語言繪制熱圖

Use custom colorscol <- colorRampPalette(c("red", "white", "blue"))(256)heatmap(df, scale = "none", col=col)

一文詳解如何用 R 語言繪制熱圖

#Use RColorBrewer color palette names

library(RColorBrewer)col <- colorRampPalette(brewer.pal(10, "RdYlBu"))(256)#自設(shè)置調(diào)色板dim(df)#查看行列數(shù)

## [1] 32 11

heatmap(df, scale = "none", col=col, RowSideColors = rep(c("blue", "pink"), each=16), 

ColSideColors = c(rep("purple", 5), rep("orange", 6)))

#參數(shù)RowSideColors和ColSideColors用于分別注釋行和列顏色等,可help(heatmap)詳情

一文詳解如何用 R 語言繪制熱圖

增強(qiáng)熱圖

函數(shù) heatmap.2()

在熱圖繪制方面提供許多擴(kuò)展,此函數(shù)包裝在 gplots 包里。

library(gplots)heatmap.2(df, scale = "none", col=bluered(100), 

trace = "none", density.info = "none")#還有其他參數(shù)可參考help(heatmap.2())

一文詳解如何用 R 語言繪制熱圖

交互式熱圖繪制

d3heatmap 包可用于生成交互式熱圖繪制,可通過以下代碼生成:

if (!require("devtools")) 

install.packages("devtools") 

devtools::install_github("rstudio/d3heatmap")

函數(shù) d3heatmap() 用于創(chuàng)建交互式熱圖,有以下功能:

● 將鼠標(biāo)放在感興趣熱圖單元格上以查看行列名稱及相應(yīng)值

● 可選擇區(qū)域進(jìn)行縮放

library(d3heatmap)d3heatmap(df, colors = "RdBu", k_row = 4, k_col = 2)

k_row、k_col分別指定用于對行列中樹形圖分支進(jìn)行著色所需組數(shù)。進(jìn)一步信息可help(d3heatmap())獲取。

使用 dendextend 包增強(qiáng)熱圖

軟件包 dendextend 可以用于增強(qiáng)其他軟件包的功能

library(dendextend)# order for rows

Rowv <- mtcars %>% scale %>% dist %>% 

hclust %>% as.dendrogram %>%

set("branches_k_color", k = 3) %>% 

set("branches_lwd", 1.2) %>% ladderize# Order for columns# 

We must transpose the data

Colv <- mtcars %>% scale %>% t %>% dist %>% 

hclust %>% as.dendrogram %>%

set("branches_k_color", k = 2, value = c("orange", "blue")) %>% set("branches_lwd", 1.2) %>% ladderize

#增強(qiáng)heatmap()函數(shù)

heatmap(df, Rowv = Rowv, Colv = Colv, scale = "none")

一文詳解如何用 R 語言繪制熱圖

#增強(qiáng)heatmap.2()函數(shù)

heatmap.2(df, scale = "none", col = bluered(100), Rowv = Rowv, Colv = Colv, trace = "none", density.info = "none")

一文詳解如何用 R 語言繪制熱圖

#增強(qiáng)交互式繪圖函數(shù)

d2heatmap()d3heatmap(scale(mtcars), colors = "RdBu", Rowv = Rowv, Colv = Colv)

繪制復(fù)雜熱圖

ComplexHeatmap 包是 bioconductor 包,用于繪制復(fù)雜熱圖,它提供了一個靈活的解決方案來安排和注釋多個熱圖。它還允許可視化來自不同來源的不同數(shù)據(jù)之間的關(guān)聯(lián)熱圖??赏ㄟ^以下代碼安裝:

if (!require("devtools")) install.packages("devtools") 

devtools::install_github("jokergoo/ComplexHeatmap")

ComplexHeatmap 包的主要功能函數(shù)是 Heatmap(),格式為:Heatmap(matrix, col, name)

● matrix:矩陣

● col:顏色向量(離散色彩映射)或顏色映射函數(shù)(如果矩陣是連續(xù)數(shù))

● name:熱圖名稱

library(ComplexHeatmap)

Heatmap(df, name = "mtcars")

一文詳解如何用 R 語言繪制熱圖

#自設(shè)置顏色

library(circlize)

Heatmap(df, name = "mtcars", col = colorRamp2(c(-2, 0, 2), c("green", "white", "red")))

使用調(diào)色板

Heatmap(df, name = "mtcars",col = colorRamp2(c(-2, 0, 2), brewer.pal(n=3, name="RdBu")))

一文詳解如何用 R 語言繪制熱圖

#自定義顏色

mycol <- colorRamp2(c(-2, 0, 2), c("blue", "white", "red"))

熱圖及行列標(biāo)題設(shè)置

Heatmap(df, name = "mtcars", col = mycol, column_title = "Column title", row_title = 

"Row title")

一文詳解如何用 R 語言繪制熱圖

注意,行標(biāo)題的默認(rèn)位置是“l(fā)eft”,列標(biāo)題的默認(rèn)是“top”??梢允褂靡韵逻x項更改:

● row_title_side:允許的值為“左”或“右”(例如:row_title_side =“right”)

● column_title_side:允許的值為“top”或“bottom”(例如:column_title_side =“bottom”) 也可以使用以下選項修改字體和大?。?/p>

● row_title_gp:用于繪制行文本的圖形參數(shù)

● column_title_gp:用于繪制列文本的圖形參數(shù)

Heatmap(df, name = "mtcars", col = mycol, column_title = "Column title", 

column_title_gp = gpar(fontsize = 14, fontface = "bold"), 

row_title = "Row title", row_title_gp = gpar(fontsize = 14, fontface = "bold"))

一文詳解如何用 R 語言繪制熱圖

在上面的R代碼中,fontface的可能值可以是整數(shù)或字符串:1 = plain,2 = bold,3 =斜體,4 =粗體斜體。如果是字符串,則有效值為:“plain”,“bold”,“italic”,“oblique”和“bold.italic”。

顯示行/列名稱:

● show_row_names:是否顯示行名稱。默認(rèn)值為TRUE

● show_column_names:是否顯示列名稱。默認(rèn)值為TRUE

Heatmap(df, name = "mtcars", show_row_names = FALSE)

一文詳解如何用 R 語言繪制熱圖

更改聚類外觀

默認(rèn)情況下,行和列是包含在聚類里的??梢允褂脜?shù)修改:

● cluster_rows = FALSE。如果為TRUE,則在行上創(chuàng)建集群

● cluster_columns = FALSE。如果為TRUE,則將列置于簇上

# Inactivate cluster on rows

Heatmap(df, name = "mtcars", col = mycol, cluster_rows = FALSE)

一文詳解如何用 R 語言繪制熱圖

如果要更改列集群的高度或?qū)挾龋梢允褂眠x項column_dend_height 和 row_dend_width:

Heatmap(df, name = "mtcars", col = mycol, column_dend_height = unit(2, "cm"), 

row_dend_width = unit(2, "cm") )

一文詳解如何用 R 語言繪制熱圖

我們還可以利用 color_branches() 自定義樹狀圖外觀

library(dendextend)

row_dend = hclust(dist(df)) # row clustering

col_dend = hclust(dist(t(df))) # column clustering

Heatmap(df, name = "mtcars", col = mycol, cluster_rows = 

color_branches(row_dend, k = 4), cluster_columns = color_branches(col_dend, k = 2))

一文詳解如何用 R 語言繪制熱圖

不同的聚類距離計算方式

參數(shù) clustering_distance_rows 和 clustering_distance_columns

用于分別指定行和列聚類的度量標(biāo)準(zhǔn),允許的值有“euclidean”, “maximum”, “manhattan”, “canberra”, “binary”, “minkowski”, “pearson”, “spearman”, “kendall”。

Heatmap(df, name = "mtcars", clustering_distance_rows = "pearson", 

clustering_distance_columns = "pearson")

一文詳解如何用 R 語言繪制熱圖

#也可以自定義距離計算方式

Heatmap(df, name = "mtcars", clustering_distance_rows = function(m) dist(m))

一文詳解如何用 R 語言繪制熱圖

Heatmap(df, name = "mtcars", clustering_distance_rows = function(x, y) 1 - cor(x, y))

一文詳解如何用 R 語言繪制熱圖

請注意,在上面的R代碼中,通常為指定行聚類的度量的參數(shù) clustering_distance_rows顯示示例。建議對參數(shù)clustering_distance_columns(列聚類的度量標(biāo)準(zhǔn))使用相同的度量標(biāo)準(zhǔn)。

# Clustering metric function

robust_dist = function(x, y) { 

qx = quantile(x, c(0.1, 0.9)) qy = quantile(y, c(0.1, 0.9)) l = x > qx[1] & x < qx[2] & y 

> qy[1] & y < qy[2] x = x[l] y = y[l] sqrt(sum((x - y)^2))}

# Heatmap

Heatmap(df, name = "mtcars", clustering_distance_rows = robust_dist, 

clustering_distance_columns = robust_dist, 

col = colorRamp2(c(-2, 0, 2), c("purple", "white", "orange")))

一文詳解如何用 R 語言繪制熱圖

聚類方法

參數(shù)clustering_method_rows和clustering_method_columns可用于指定進(jìn)行層次聚類的方法。允許的值是hclust()函數(shù)支持的值,包括“ward.D”,“ward.D2”,“single”,“complete”,“average”。

Heatmap(df, name = "mtcars", clustering_method_rows = "ward.D", 

clustering_method_columns = "ward.D")

一文詳解如何用 R 語言繪制熱圖

熱圖拆分

有很多方法來拆分熱圖。一個解決方案是應(yīng)用k-means使用參數(shù)km。

在執(zhí)行k-means時使用set.seed()函數(shù)很重要,這樣可以在稍后精確地再現(xiàn)結(jié)果

set.seed(1122)

# split into 2 groupsHeatmap(df, name = "mtcars", col = mycol, k = 2)

一文詳解如何用 R 語言繪制熱圖

# split by a vector specifying row classes, 有點類似于ggplot2里的分面

Heatmap(df, name = "mtcars", col = mycol, split = mtcars$cyl )

一文詳解如何用 R 語言繪制熱圖

#split也可以是一個數(shù)據(jù)框,其中不同級別的組合拆分熱圖的行。

# Split by combining multiple variables

Heatmap(df, name ="mtcars", col = mycol, split = data.frame(cyl = mtcars$cyl, am = mtcars$am))

一文詳解如何用 R 語言繪制熱圖

# Combine km and split

Heatmap(df, name ="mtcars", col = mycol, km = 2, split = mtcars$cyl)

一文詳解如何用 R 語言繪制熱圖

#也可以自定義分割

library("cluster")

set.seed(1122)

pa = pam(df, k = 3)Heatmap(df, name = "mtcars", col = mycol, split = paste0("pam", 

pa$clustering))

一文詳解如何用 R 語言繪制熱圖

還可以將用戶定義的樹形圖和分割相結(jié)合。在這種情況下,split可以指定為單個數(shù)字:

row_dend = hclust(dist(df)) # row clusterin

grow_dend = color_branches(row_dend, k = 4)

Heatmap(df, name = "mtcars", col = mycol, cluster_rows = row_dend, split = 2)

一文詳解如何用 R 語言繪制熱圖

熱圖注釋

利用HeatmapAnnotation()對行或列注釋。格式為: HeatmapAnnotation(df, name, col, show_legend)

● df:帶有列名的data.frame

● name:熱圖標(biāo)注的名稱

● col:映射到df中列的顏色列表

# Transposedf <- t(df)

# Heatmap of the transposed data

Heatmap(df, name ="mtcars", col = mycol)

一文詳解如何用 R 語言繪制熱圖

# Annotation data frame

annot_df <- data.frame(cyl = mtcars$cyl, am = mtcars$am, mpg = mtcars$mpg)

# Define colors for each levels of qualitative variables

# Define gradient color for continuous variable (mpg)

col = list(cyl = c("4" = "green", "6" = "gray", "8" = "darkred"), am = c("0" = "yellow", 

"1" = "orange"), mpg = colorRamp2(c(17, 25), c("lightblue", "purple")) )

# Create the heatmap annotation

ha <- HeatmapAnnotation(annot_df, col = col)

# Combine the heatmap and the annotation

Heatmap(df, name = "mtcars", col = mycol, top_annotation = ha)

一文詳解如何用 R 語言繪制熱圖

#可以使用參數(shù)show_legend = FALSE來隱藏注釋圖例

ha <- HeatmapAnnotation(annot_df, col = col, show_legend = FALSE)

Heatmap(df, name = "mtcars", col = mycol, top_annotation = ha)

一文詳解如何用 R 語言繪制熱圖

#注釋名稱可以使用下面的R代碼添加

library("GetoptLong")

# Combine Heatmap and annotation

ha <- HeatmapAnnotation(annot_df, col = col, show_legend = FALSE)

Heatmap(df, name = "mtcars", col = mycol, top_annotation = ha)

# Add annotation names on the right

for(an in colnames(annot_df)) { 

seekViewport(qq("annotation_@{an}")) 

grid.text(an, unit(1, "npc") + unit(2, "mm"), 0.5, default.units = "npc", just = "left")}

#要在左側(cè)添加注釋名稱,請使用以下代碼

# Annotation names on the left

for(an in colnames(annot_df)) { seekViewport(qq("annotation_@{an}")) grid.text(an, 

unit(1, "npc") - unit(2, "mm"), 0.5, default.units = "npc", just = "left")}

一文詳解如何用 R 語言繪制熱圖

復(fù)雜注釋

將熱圖與一些基本圖形結(jié)合起來進(jìn)行注釋,利用anno_point(),anno_barplot(),anno_boxplot(),anno_density() 和 anno_histogram()。

# Define some graphics to display the distribution of columns

.hist = anno_histogram(df, gp = gpar(fill = "lightblue"))

.density = anno_density(df, type = "line", gp = gpar(col = "blue"))

ha_mix_top = HeatmapAnnotation(hist = .hist, density = .density)

# Define some graphics to display the distribution of rows

.violin = anno_density(df, type = "violin", gp = gpar(fill = "lightblue"), which = "row")

.boxplot = anno_boxplot(df, which = "row")

ha_mix_right = HeatmapAnnotation(violin = .violin, bxplt = .boxplot, which = "row", 

width = unit(4, "cm"))

# Combine annotation with heatmap

Heatmap(df, name = "mtcars", col = mycol, column_names_gp = gpar(fontsize = 8), 

top_annotation = ha_mix_top, top_annotation_height = unit(4, "cm")) + ha_mix_right

一文詳解如何用 R 語言繪制熱圖

熱圖組合

# Heatmap 1

ht1 = Heatmap(df, name = "ht1", col = mycol, km = 2, column_names_gp = gpar(fontsize = 9))

# Heatmap 2

ht2 = Heatmap(df, name = "ht2", col = colorRamp2(c(-2, 0, 2), c("green", "white", "red")), column_names_gp = gpar(fontsize = 9))

# Combine the two heatmaps

ht1 + ht2

一文詳解如何用 R 語言繪制熱圖

可以使用選項width = unit(3,“cm”))來控制熱圖大小。注意,當(dāng)組合多個熱圖時,第一個熱圖被視為主熱圖。剩余熱圖的一些設(shè)置根據(jù)主熱圖的設(shè)置自動調(diào)整。這些設(shè)置包括:刪除行集群和標(biāo)題,以及添加拆分等。

draw(ht1 + ht2, 

      # Titles 

     row_title = "Two heatmaps, row title",

     row_title_gp = gpar(col = "red"), 

     column_title = "Two heatmaps, column title", 

     column_title_side = "bottom", 

      # Gap between heatmaps 

     gap = unit(0.5, "cm"))

一文詳解如何用 R 語言繪制熱圖

可以使用參數(shù)show_heatmap_legend = FALSE,show_annotation_legend = FALSE刪除圖例。

基因表達(dá)矩陣

在基因表達(dá)數(shù)據(jù)中,行代表基因,列是樣品值。關(guān)于基因的更多信息可以在表達(dá)熱圖之后附加,例如基因長度和基因類型。

expr = readRDS(paste0(system.file(package = "ComplexHeatmap"), "/extdata/gene_expression.rds"))

mat = as.matrix(expr[, grep("cell", colnames(expr))])

type = gsub("s\\d+_", "", colnames(mat))

ha = HeatmapAnnotation(df = data.frame(type = type))

Heatmap(mat, name = "expression", km = 5, top_annotation = ha, top_annotation_height = unit(4, "mm"), 

show_row_names = FALSE, show_column_names = FALSE) +

Heatmap(expr$length, name = "length", width = unit(5, "mm"), col = colorRamp2(c(0, 100000), c("white", "orange"))) +

Heatmap(expr$type, name = "type", width = unit(5, "mm")) +

Heatmap(expr$chr, name = "chr", width = unit(5, "mm"), col = rand_color(length(unique(expr$chr))))

一文詳解如何用 R 語言繪制熱圖

也可以可視化基因組變化和整合不同的分子水平(基因表達(dá),DNA甲基化,…)

可視化矩陣中列的分布

使用函數(shù)densityHeatmap()。

densityHeatmap(df)

一文詳解如何用 R 語言繪制熱圖

8 Infos

sessionInfo()

## R version 3.3.3 (2017-03-06)

## Platform: x86_64-w64-mingw32/x64 (64-bit)

## Running under: Windows 8.1 x64 (build 9600)## 

## locale:

## [1] LC_COLLATE=Chinese (Simplified)_China.936 

## [2] LC_CTYPE=Chinese (Simplified)_China.936 

## [3] LC_MONETARY=Chinese (Simplified)_China.936

## [4] LC_NUMERIC=C 

## [5] LC_TIME=Chinese (Simplified)_China.936 ##

 ## attached base packages:

## [1] grid stats graphics grDevices utils datasets methods 

## [8] base 

## 

## other attached packages:

## [1] GetoptLong_0.1.6 cluster_2.0.5 circlize_0.3.10 

## [4] ComplexHeatmap_1.12.0 dendextend_1.4.0 d3heatmap_0.6.1.1

##[7] gplots_3.0.1 RColorBrewer_1.1-2 

## 

## loaded via a namespace (and not attached):

## [1] Rcpp_0.12.9 DEoptimR_1.0-8 plyr_1.8.4 

## [4] viridis_0.3.4 class_7.3-14 prabclus_2.2-6 

## [7] bitops_1.0-6 base64enc_0.1-3 tools_3.3.3 

## [10] digest_0.6.12 mclust_5.2.2 jsonlite_1.3 

## [13] evaluate_0.10 tibble_1.2 gtable_0.2.0 

## [16] lattice_0.20-34 png_0.1-7 yaml_2.1.14 

## [19] mvtnorm_1.0-6 gridExtra_2.2.1 trimcluster_0.1-2 

## [22] stringr_1.2.0 knitr_1.15.1 GlobalOptions_0.0.11

## [25] htmlwidgets_0.8 gtools_3.5.0 caTools_1.17.1 

## [28] fpc_2.1-10 diptest_0.75-7 nnet_7.3-12 

## [31] stats4_3.3.3 rprojroot_1.2 robustbase_0.92-7 

## [34] flexmix_2.3-13 rmarkdown_1.3.9002 gdata_2.17.0 

## [37] kernlab_0.9-25 ggplot2_2.2.1 magrittr_1.5 

## [40] whisker_0.3-2 backports_1.0.5 scales_0.4.1 

## [43] htmltools_0.3.5 modeltools_0.2-21 MASS_7.3-45

## [46] assertthat_0.1 shape_1.4.2 colorspace_1.3-2 

## [49] KernSmooth_2.23-15 stringi_1.1.2 lazyeval_0.2.0 

## [52] munsell_0.4.3 rjson_0.2.15

雷鋒網(wǎng)相關(guān)閱讀:

用數(shù)據(jù)說話,R語言有哪七種可視化應(yīng)用?

Python vs R : 在機(jī)器學(xué)習(xí)和數(shù)據(jù)分析領(lǐng)域中的對比

雷峰網(wǎng)版權(quán)文章,未經(jīng)授權(quán)禁止轉(zhuǎn)載。詳情見轉(zhuǎn)載須知。

一文詳解如何用 R 語言繪制熱圖

分享:
相關(guān)文章

編輯

聚焦數(shù)據(jù)科學(xué),連接 AI 開發(fā)者。更多精彩內(nèi)容,請訪問:yanxishe.com
當(dāng)月熱門文章
最新文章
請?zhí)顚懮暾埲速Y料
姓名
電話
郵箱
微信號
作品鏈接
個人簡介
為了您的賬戶安全,請驗證郵箱
您的郵箱還未驗證,完成可獲20積分喲!
請驗證您的郵箱
立即驗證
完善賬號信息
您的賬號已經(jīng)綁定,現(xiàn)在您可以設(shè)置密碼以方便用郵箱登錄
立即設(shè)置 以后再說