Un mapa de calor (o mapa de calor) es otra forma de visualizar la agrupación jerárquica. Es también llamada imagen de color falso, donde los valores de los datos se transforman a escala de color. Los mapas de calor nos permiten visualizar simultáneamente grupos de muestras y características. Primero La agrupación jerárquica se realiza tanto para las filas como para las columnas de la matriz de datos.
Hay un número múltiple de paquetes y funciones de R para dibujar de forma interactiva y mapas de calor estáticos, que incluyen: heatmap() [R base function, stats package]: Traza un mapa de calor simple. heatmap.2() [gplots R package]: Dibuja un mapa de calor mejorado en comparación con la función base de R pheatmap()[pheatmap R package]:dibuja bonitos mapas de calor y proporciona más control para cambiar la apariencia de los mapas de calor. d3heatmap()[d3heatmap R package]: Dibuja un calor interactivo Heatmap() {ComplexHeatmap R/Bioconductor package]:Dibuja, anota y organiza mapas de calor complejos (muy útil para el análisis de datos genómicos)
Aquí, comenzamos describiendo las 5 funciones R para dibujar mapas de calor. A continuación, Nos centramos en el paquete CompletHeatmap, que proporciona una solución flexible para organizar y anotar múltiples mapas de calor. Permite también visualizar la asociación entre diferentes datos de diferentes fuentes.
Usamos datos de intcars como un conjunto de datos demo. Comenzamos estandarizando los datos para hacer variables comparables:
df <- scale(mtcars)
Se puede usar la función integrada R heatmap() [en el paquete de stats]. Un formato simplificado es:
#heatmap(x =, scale = "row")
x: una matriz numérica scale: un carácter que indica si los valores deben estar centrados y escalados en ya sea la dirección de la fila o la dirección de la columna, o ninguna. Los valores permitidos están en c(“row”, “column”, “none”). El valor predeterminado es “row”
heatmap(df, scale = "none")
En la gráfica de arriba, los valores altos están en rojo y los valores bajos están en amarillo. Es posible especificar una paleta de colores usando el argumento col, que se puede definir como: • Uso de colores personalizados:
col<- colorRampPalette(c("red", "white", "blue"))(256)
• O, utilizando la paleta de colores RColorBrewer:
library("RColorBrewer")
col <- colorRampPalette(brewer.pal(10, "RdYlBu"))(256)
Además, puede usar el argumento RouSide Colors y ColSide Colors para anotar filas y columnas, respectivamente
library("RColorBrewer")
col <- colorRampPalette(brewer.pal(10, "RdYlBu"))(256)
heatmap(df, scale = "none", col = col,
RowSideColors = rep(c("blue", "pink"), each = 16),
ColSideColors = c(rep("purple", 5), rep("orange", 6)))
La función heatmap.2() [en el paquete gplots] proporciona muchas extensiones a la función estandar R heatmap() presentada en la sección anterior.
library("gplots")
##
## Attaching package: 'gplots'
## The following object is masked from 'package:stats':
##
## lowess
heatmap.2(df, scale = "none", col = bluered(100),
trace = "none", density.info = "none")
Se pueden usar otros argumentos, incluidos: + labRow, labCol + helustfun: helustfun=función(x) hclust(x, method = “ward”) En el código R. anterior, la función bluered() del paquete gplots se usa para generar un conjunto de colores que varía suavemente.
Primero, instale el paquete pheatmap: install.packages(“pheatmap”)
library("pheatmap")
pheatmap(df, cutree_rows = 4)
Hay argumentos disponibles para cambiar la métrica de agrupación predeterminada (“euclidean”) y el method(“complete”). También es posible anotar filas y columnas utilizando variables de agrupación.
Primero, instale el paquete d3heatmap: instalar paquetes (“d3heatmap”)
if (!require("devtools")) install.packages("devtools")
## Loading required package: devtools
## Loading required package: usethis
if (!require("d3heatmap")) {
chooseCRANmirror() # Establecer un repositorio de CRAN válido
devtools::install_github("rstudio/d3heatmap")
}
## Loading required package: d3heatmap
##
## ======================
## Welcome to d3heatmap version 0.9.0
##
## Type citation('d3heatmap') for how to cite the package.
## Type ?d3heatmap for the main documentation.
##
## The github page is: https://github.com/talgalili/d3heatmap/
## Please submit your suggestions and bug-reports at: https://github.com/talgalili/d3heatmap/issues
## You may ask questions at stackoverflow, use the r and d3heatmap tags:
## https://stackoverflow.com/questions/tagged/d3heatmap
## ======================
##
## Attaching package: 'd3heatmap'
## The following objects are masked from 'package:base':
##
## print, save
library("d3heatmap")
d3heatmap(scale(mtcars), colors = "RdYlBu",
k_row = 4, # Number of groups in rows
k_col = 2) # Number of groups in columns
## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette RdYlBu is 11
## Returning the palette you asked for with that many colors
## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette RdYlBu is 11
## Returning the palette you asked for with that many colors
’La función d3heamap() hace posible + Colocar el cursor en una celda del mapa de calor que le interese para ver los nombres de fila y columna, así como el valor correspondiente. + Seleccione un área para hacer zoom. Después de hacer zoom, haga clic en el mapa de calor nuevamente para volver a la pantalla anterior
El paquete dendextend se puede utilizar para mejorar las funciones de otros paquetes. Los datos de mtcars se utilizan en las siguientes secciones. Comenzaremos definiendo el orden y la apariencia de filas y columnas usando dendextend. Estos resultados se utilizan en otras funciones de otros paquetes. El orden y la apariencia de filas y columnas se pueden definir como:
library(dendextend)
##
## ---------------------
## Welcome to dendextend version 1.17.1
## Type citation('dendextend') for how to cite the package.
##
## Type browseVignettes(package = 'dendextend') for the package vignette.
## The github page is: https://github.com/talgalili/dendextend/
##
## Suggestions and bug-reports can be submitted at: https://github.com/talgalili/dendextend/issues
## You may ask questions at stackoverflow, use the r and dendextend tags:
## https://stackoverflow.com/questions/tagged/dendextend
##
## To suppress this message use: suppressPackageStartupMessages(library(dendextend))
## ---------------------
##
## Attaching package: 'dendextend'
## The following object is masked from 'package:stats':
##
## cutree
# 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
Los argumentos anteriores se pueden utilizar en las siguientes funciones:
heatmap(scale(mtcars), Rowv = Rowv, Colv = Colv,
scale = "none")
library(gplots)
heatmap.2(scale(mtcars), scale = "none", col = bluered(100),
Rowv = Rowv, Colv = Colv,
trace = "none", density.info = "none")
library("d3heatmap")
d3heatmap(scale(mtcars), colors = "RdBu",
Rowv = Rowv, Colv = Colv)
## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette RdYlBu is 11
## Returning the palette you asked for with that many colors
## Warning in RColorBrewer::brewer.pal(n, pal): n too large, allowed maximum for palette RdYlBu is 11
## Returning the palette you asked for with that many colors
ComplexHeatmap es un paquete R/bioconductor, desarrollado por Zuguang Gu, que proporciona una solución flexible para organizar y anotar múltiples mapas de calor. También permite visualizar la asociación entre diferentes datos de diferentes fuentes. Así puede ser instalado
if (!require("BiocManager", quietly = TRUE))
install.packages("BiocManager")
##
## Attaching package: 'BiocManager'
## The following object is masked from 'package:devtools':
##
## install
BiocManager::install("ComplexHeatmap")
## Bioconductor version 3.17 (BiocManager 1.30.20), R 4.3.0 (2023-04-21 ucrt)
## Warning: package(s) not installed when version(s) same as or greater than current; use
## `force = TRUE` to re-install: 'ComplexHeatmap'
## Installation paths not writeable, unable to update packages
## path: C:/Program Files/R/R-4.3.0/library
## packages:
## class, KernSmooth, MASS, Matrix, nnet
## Old packages: 'tseries'
Se puede trazar un mapa de calor simple de esta manera:
library(ComplexHeatmap)
## Loading required package: grid
## ========================================
## ComplexHeatmap version 2.16.0
## Bioconductor page: http://bioconductor.org/packages/ComplexHeatmap/
## Github page: https://github.com/jokergoo/ComplexHeatmap
## Documentation: http://jokergoo.github.io/ComplexHeatmap-reference
##
## If you use it in published research, please cite either one:
## - Gu, Z. Complex Heatmap Visualization. iMeta 2022.
## - Gu, Z. Complex heatmaps reveal patterns and correlations in multidimensional
## genomic data. Bioinformatics 2016.
##
##
## The new InteractiveComplexHeatmap package can directly export static
## complex heatmaps into an interactive Shiny app with zero effort. Have a try!
##
## This message can be suppressed by:
## suppressPackageStartupMessages(library(ComplexHeatmap))
## ========================================
## ! pheatmap() has been masked by ComplexHeatmap::pheatmap(). Most of the arguments
## in the original pheatmap() are identically supported in the new function. You
## can still use the original function by explicitly calling pheatmap::pheatmap().
##
## Attaching package: 'ComplexHeatmap'
## The following object is masked from 'package:pheatmap':
##
## pheatmap
Heatmap(df,
name = "mtcars", #title of legend
column_title = "Variables", row_title = "Samples",
row_names_gp = gpar(fontsize = 7) # Text size for row names
)
Para especificar colores personalizados, debe usar la función colorRamp2() [del paquete circlize], de la siguiente manera:
library(circlize)
## ========================================
## circlize version 0.4.15
## CRAN page: https://cran.r-project.org/package=circlize
## Github page: https://github.com/jokergoo/circlize
## Documentation: https://jokergoo.github.io/circlize_book/book/
##
## If you use it in published research, please cite:
## Gu, Z. circlize implements and enhances circular visualization
## in R. Bioinformatics 2014.
##
## This message can be suppressed by:
## suppressPackageStartupMessages(library(circlize))
## ========================================
mycols <- colorRamp2(breaks = c(-2, 0, 2),
colors = c("green", "white", "red"))
Heatmap(df, name = "mtcars", col = mycols)
También es posible utilizar paletas de colores RColorBrewer:
library("circlize")
library("RColorBrewer")
Heatmap(df, name = "mtcars",
col = colorRamp2(c(-2, 0, 2), brewer.pal(n=3, name="RdBu")))
También podemos personalizar la apariencia de los dendogramas usando la función color_branches() [Del paquete dendextend]:
library(dendextend)
row_dend = hclust(dist(df)) # row clustering
col_dend = hclust(dist(t(df))) # column clustering
Heatmap(df, name = "mtcars",
row_names_gp = gpar(fontsize = 6.5),
cluster_rows = color_branches(row_dend, k = 4),
cluster_columns = color_branches(col_dend, k = 2))
Puede dividir el mapa de calor utilizando el algoritmo k-means o una variable de agrupación. Es importante utilizar la función set.seed() al realizar k-means para que los resultados obtenidos puedan reproducirse con precisión en un momento posterior. + Para dividir el dendrograma usando k-means, escriba esto
#Divide into 2 groups
set.seed(2)
Heatmap(df, name = "mtcars", k = 2)
Heatmap(df, name = "mtcars", split = mtcars$cyl,
row_names_gp = gpar(fontsize = 7))
Tenga en cuenta que split también puede ser un marco de datos en el que diferentes combinaciones de niveles dividen las filas del mapa de calor.
#Split by combining multiple variables
Heatmap(df, name ="mtcars",
split = data.frame(cyl = mtcars$cyl, am = mtcars$am))
La clase HeatmapAnnotation se usa para definir la anotación en una fila o columna. Un formato simplificado es:
#HeatmapAnnotation(df, name, col, show_legend)
df <- t(df)
Un vector, que contiene valores discretos o continuos, se usa para anotar filas o columnas. Usaremos las variables cualitativas cyl (levels = “4°,”57 y “8”) y am(levels = “0” y “1”), y la variable continua mpg para anotar columnas. Para cada una de estas 3 variables, los colores personalizados se definen de la siguiente manera:
datos <- t(scale(mtcars))
annot_df <- data.frame(cyl = mtcars$cyl, am = mtcars$am,mpg = mtcars$mpg)
library(circlize)
col = list(cyl = c("4" = "green", "6" = "gray", "8" = "darkred"),
am = c("0" = "yellow", "1" = "orange"),
mpg = circlize::colorRamp2(c(17, 25),
c("lightblue", "purple")) )
ha <- HeatmapAnnotation(df = annot_df, col = col)
Heatmap( matrix = datos, name = "mtcars", top_annotation = ha )
Es posible ocultar la leyenda de la anotación usando el argumento show legend = FALSE, de la siguiente manera:
ha <- HeatmapAnnotation(df = annot_df, col = col, show_legend = FALSE)
Heatmap(matrix = datos, name = "mtcars", top_annotation = ha )
En esta sección, veremos cómo combinar el mapa de calor y algunos gráficos básicos para mostrar la distribución de datos. Para gráficos de anotaciones simples, las siguientes funciones: se pueden utilizar: anno_points(), anno_barplot(), anno_boxplot(), anno_density() y anno_histogram(). A continuación se muestra un ejemplo
library(devtools)
install_github("jokergoo/ComplexHeatmap")
## Downloading GitHub repo jokergoo/ComplexHeatmap@HEAD
##
## ── R CMD build ─────────────────────────────────────────────────────────────────
##
checking for file 'C:\Users\angel\AppData\Local\Temp\Rtmpwd9JGl\remotes530c2e35139e\jokergoo-ComplexHeatmap-ae0ec42/DESCRIPTION' ...
✔ checking for file 'C:\Users\angel\AppData\Local\Temp\Rtmpwd9JGl\remotes530c2e35139e\jokergoo-ComplexHeatmap-ae0ec42/DESCRIPTION'
##
─ preparing 'ComplexHeatmap': (4.4s)
## checking DESCRIPTION meta-information ...
checking DESCRIPTION meta-information ...
✔ checking DESCRIPTION meta-information
##
─ checking for LF line-endings in source and make files and shell scripts (753ms)
##
─ checking for empty or unneeded directories
##
─ building 'ComplexHeatmap_2.15.4.tar.gz'
##
##
## Warning: package 'ComplexHeatmap' is in use and will not be installed
install.packages("ComplexHeatmap")
## Warning: package 'ComplexHeatmap' is in use and will not be installed
library(grid)
if (!require("BiocManager", quietly = TRUE))
install.packages("BiocManager")
BiocManager::install("ComplexHeatmap")
## Bioconductor version 3.17 (BiocManager 1.30.20), R 4.3.0 (2023-04-21 ucrt)
## Warning: package(s) not installed when version(s) same as or greater than current; use
## `force = TRUE` to re-install: 'ComplexHeatmap'
## Installation paths not writeable, unable to update packages
## path: C:/Program Files/R/R-4.3.0/library
## packages:
## class, KernSmooth, MASS, Matrix, nnet
## Old packages: 'tseries'
library(ComplexHeatmap)
# Define some graphics to display the distribution of columnsa
.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", column_names_gp = gpar(fontsize = 8),
top_annotation = ha_mix_top)+ ha_mix_right
Se pueden organizar múltiples mapas de calor de la siguiente manera:
# Heatmap 1
ht1 = Heatmap(df, name = "ht1", km = 2,
column_names_gp = gpar(fontsize = 9))
# Heatmap 2
ht2 = Heatmap(df, name = "ht2",
col = circlize::colorRamp2(c(-2, 0, 2), c("green", "white", "red")),
column_names_gp = gpar(fontsize = 9))
Y los combinamos:
ht1 + ht2
Tenga en cuenta que al combinar varios mapas de calor, el primer mapa de calor se considera el mapa de calor principal. Algunas configuraciones de los mapas de calor restantes se ajustan automáticamente de acuerdo con la configuración del mapa de calor principal. Estos incluyen: eliminar grupos de filas y títulos, y agregar división
La función draw() se puede usar para personalizar la apariencia de la imagen final:
draw(ht1 + ht2,
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"))
En los datos de expresión génica, las filas son genes y las columnas, muestras. Se puede adjuntar más información sobre los genes puede adjuntarse después del mapa térmico de expresión, como la longitud del gen y el tipo de genes.
datos <- t(scale(mtcars))
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,
show_row_names = FALSE, show_column_names = FALSE) +
Heatmap(expr$length, name = "length", width = unit(5, "mm"),
col = circlize::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 = circlize::rand_color(length(unique(expr$chr))))
## There are 23 unique colors in the vector `col` and 23 unique values in
## `matrix`. `Heatmap()` will treat it as an exact discrete one-to-one
## mapping. If this is not what you want, slightly change the number of
## colors, e.g. by adding one more color or removing a color.
Describimos muchas funciones para dibujar mapas de calor en R (desde mapas de calor básicos hasta complejos). Se puede producir un mapa de calor básico usando la función base de R heatmap() o la función heatmap.2() {en el paquete gplots). La función pheatmap(), en el paquete del mismo nombre, crea bonitos mapas de calor, donde uno tiene un mejor control sobre algunos parámetros gráficos como el tamaño de celda. La función Heatmap() [en el paquete ComplerHeatmap] nos permite dibujar, anotar y organizar fácilmente mapas de calor complejos. Esto podría ser muy útil en los campos de la genómica.