6 Heatmap
You will see a heatmap in almost every genomics paper. They look simple. They are not: the same data can give very different pictures depending on three choices (scaling, color mapping and clustering), and most people never check them.
A heatmap is a way to visualize the data a.k.a. using colors to represent values. I recommend you to read Points of view: Mapping quantitative data to color (Gehlenborg and Wong 2012b) and Points of view: Heat maps (Gehlenborg and Wong 2012a) from a series of articles from Nature Methods.
In essence, a heatmap is a rectangular grid with many small grids filled with colors corresponding to numeric or categorical values. Of course, it has many variants. You can replace the grid with circles as shown in Figure 6.1.
see details from my blog post https://divingintogeneticsandgenomics.rbind.io/post/clustered-dotplot-for-single-cell-rnaseq/.
Usually one has a matrix and then plots the matrix using functions such as heatmap.2, pheatmap or the almighty Heatmap from the ComplexHeatmap package developed by Zuguang Gu. It is full of functions and flexible to use. More importantly, the documentation is top-notch. I now use it exclusively for all my heatmaps.
6.1 A simple use case of heatmap with discrete data
I will start with a very simple use case for heatmap. We have sequenced 20 samples and identified mutations in 10 genes. some samples have the mutation in this gene, some samples do not have it. In this case, it will be a simple 0 or 1 to represent each data point. I am going to use ggplot2 for this purpose, although the base R function rect can also draw rectangles.
library(dplyr)
library(tidyr)
library(ggplot2)
library(RColorBrewer) ## better color schema
library(ggthemes)
set.seed(1)
# repeat the sampling
mut<- replicate(20, sample(c(0,1), 10, replace=TRUE))
mut<- as.data.frame(mut)
colnames(mut)<- paste0("sample", 1:20)
mut<- mut %>% mutate(gene=paste0("gene", 1:10))
head(mut)#> sample1 sample2 sample3 sample4 sample5 sample6 sample7 sample8 sample9
#> 1 0 0 0 1 1 1 0 1 1
#> 2 1 0 0 1 1 0 1 1 1
#> 3 0 0 0 0 0 1 1 0 0
#> 4 0 0 0 1 1 1 1 0 0
#> 5 1 0 0 0 1 0 1 0 0
#> 6 0 1 0 0 1 0 1 1 1
#> sample10 sample11 sample12 sample13 sample14 sample15 sample16 sample17
#> 1 0 1 0 1 0 1 1 0
#> 2 0 1 0 1 0 0 0 0
#> 3 1 1 0 0 1 0 0 0
#> 4 1 0 1 0 0 1 0 1
#> 5 0 0 1 1 1 0 0 0
#> 6 0 0 1 0 0 1 1 0
#> sample18 sample19 sample20 gene
#> 1 0 1 0 gene1
#> 2 0 0 1 gene2
#> 3 1 0 0 gene3
#> 4 0 0 1 gene4
#> 5 0 0 1 gene5
#> 6 1 0 1 gene6
Tidy the data to the long format.
mut.tidy<- mut %>%
tidyr::gather(sample, mutated, 1:20)
## change the levels for gene names and sample names so it goes 1,2,3,4... rather than 1, 10...
mut.tidy$gene<- factor(mut.tidy$gene, levels = paste0("gene", 1:10))
mut.tidy$sample<- factor(mut.tidy$sample, levels = paste0("sample", 1:20))
head(mut.tidy)#> gene sample mutated
#> 1 gene1 sample1 0
#> 2 gene2 sample1 1
#> 3 gene3 sample1 0
#> 4 gene4 sample1 0
#> 5 gene5 sample1 1
#> 6 gene6 sample1 0
when fill the tiles with color, in this case, it is 0 or 1 discrete value. R thinks mutated is a numeric continuous value, change it to factor:
mut.tidy$mutated<- factor(mut.tidy$mutated)## use a white border of size 0.5 unit to separate the tiles
gg<- ggplot(mut.tidy, aes(x=sample, y=gene, fill=mutated)) +
geom_tile(color="white", linewidth=0.5)
gg<- gg + scale_fill_brewer(palette = "Set1", direction = -1)
## geom_tile() draws rectangles, add coord_equal to draw squares.
gg<- gg + coord_equal()
## add title
gg<- gg + labs(x=NULL, y=NULL, title="mutation spectrum of 20 breast cancers")
##starting with a base theme of theme_tufte() from the ggthemes package. It removes a lot of chart junk without having to do it manually.
gg <- gg + theme_tufte(base_family="Helvetica")
#We don’t want any tick marks on the axes and I want the text to be slightly smaller than the default.
gg <- gg + theme(axis.ticks=element_blank())
gg <- gg + theme(axis.text.x=element_text(angle = 45, hjust = 1))
gg
If you want to manually fill the color, you can use scale_fill_manual, and check http://colorbrewer2.org/ to get the HEX representation of the color.
ggplot(mut.tidy, aes(x=sample, y=gene, fill=mutated)) +
geom_tile(color="white", linewidth=0.5) +
coord_equal() +
labs(x=NULL, y=NULL, title="mutation spectrum of 20 breast cancers") +
theme_tufte(base_family="Helvetica") +
scale_fill_manual(values = c("#7570b3", "#1b9e77")) +
theme(axis.ticks=element_blank()) +
theme(axis.text.x=element_text(angle = 45, hjust = 1))
Note that in a real genomic experiment, thousands of genes will be assayed, and one can use tools such as CoMET or SELECT to find the mutual exclusive mutations and plot as I just did. There is a so called oncoprint in many papers and essentially they are doing the same thing as I did here, but adding many details. see one example from ComplexHeatmap.
6.2 Use heatmap to represent continuous values
I showed an example of using heatmap to represent discrete values (yes or no mutation). I will show you how to use heatmap to represent continuous values and do clustering on rows and columns to find patterns (unsupervised clustering). ggplot2 itself does not have clustering built-in. We will have to use the functions I mentioned in the beginning of this chapter.
6.3 Clustering
Clustering is used to find patterns of your data, it is one of the unsupervised machine learning techniques.
There are many clustering methods such as k-means and hierarchical clustering.
In hierarchical clustering, a dendrogram (Figure 6.2) is the tree you see on the side of a heatmap. Two samples that join low down are similar; the height where two branches join is the distance between them. Flip any branch around its joint and the tree means exactly the same thing.
6.4 Distance measures
Before doing clustering, one has to define the distances between data points first. There are different distance measures as shown in Figure 6.3. Credit https://medium.com/data-science/9-distance-measures-in-data-science-918109d069fa.
Many of the distances can be calculated with the dist function in R:
6.5 Linkages
After you define the distance measure, one has to define how the clusters are merged. That’s what linkage does.
Linkage: Measure of dissimilarity between two sets of objects that determine how two set of objects are merged.
Single linkage: Minimum dissimilarity between points in two sets used to determine which two sets should be merged.
Complete linkage: Maximum dissimilarity between points in two sets used to determine which two sets should be merged.
Average Linkage: Average dissimilarity between points in two sets used to determine which two sets should be merged.
Ward’s Linkage. The idea has much in common with analysis of variance (ANOVA). The linkage function specifying the distance between two clusters is computed as the increase in the “error sum of squares” (ESS) after fusing two clusters into a single cluster.
Read more on clustering: https://www.nature.com/articles/nmeth.4299
Let’s use the NCI data again as we used in the Chapter 5.
library(ISLR)
ncidat<- t(NCI60$data)
colnames(ncidat)<- NCI60$labs
dim(ncidat)#> [1] 6830 64
ncidat[1:10, 1:5]#> CNS CNS CNS RENAL BREAST
#> 1 0.3000000 0.67996100 0.9400000 2.800000e-01 0.485000
#> 2 1.1800000 1.28996100 -0.0400000 -3.100000e-01 -0.465000
#> 3 0.5500000 0.16996100 -0.1700000 6.800000e-01 0.395000
#> 4 1.1400000 0.37996100 -0.0400000 -8.100000e-01 0.905000
#> 5 -0.2650000 0.46496100 -0.6050000 6.250000e-01 0.200000
#> 6 -0.0700000 0.57996100 0.0000000 -1.387779e-17 -0.005000
#> 7 0.3500000 0.69996100 0.0900000 1.700000e-01 0.085000
#> 8 -0.3150000 0.72496100 0.6450000 2.450000e-01 0.110000
#> 9 -0.4500000 -0.04003899 0.4300000 2.000000e-02 0.235000
#> 10 -0.6549805 -0.28501950 0.4750195 9.501949e-02 1.490019
unique(colnames(ncidat))#> [1] "CNS" "RENAL" "BREAST" "NSCLC" "UNKNOWN"
#> [6] "OVARIAN" "MELANOMA" "PROSTATE" "LEUKEMIA" "K562B-repro"
#> [11] "K562A-repro" "COLON" "MCF7A-repro" "MCF7D-repro"
X<- t(scale(t(ncidat),center=TRUE,scale=FALSE))Let’s uses complete linkage:
- Often gives comparable cluster sizes.
- Less sensitive to outliers.
- Works better with spherical distributions.
cols<- as.numeric(as.factor(colnames(ncidat)))
#default euclidean distance
Dmat<- dist(t(ncidat))
com.hclust<- hclust(Dmat,method="complete")
plot(com.hclust,cex=.7,main="Complete Linkage")
Bonus read this blog post to understand the hclust object https://jokergoo.github.io/2023/07/07/what-is-a-hclust-object/
Let’s make the dendrogram look a little better by coloring the labels.
# https://cran.r-project.org/web/packages/dendextend/vignettes/dendextend.html
# better dendrogram
library(dendextend)
#https://cran.r-project.org/web/packages/Polychrome/index.html
# better color
library(Polychrome)
set.seed(12042022)
mypal <- kelly.colors(15)
swatch(mypal)
# remove the white color
mypal<- mypal[-1]
dend<- com.hclust %>%
as.dendrogram()
dend_labels<- dend %>% labels()
dend %>%
color_labels(col = mypal[as.numeric(as.factor(dend_labels))]) %>%
set("labels_cex", 0.7) %>%
plot()
Make a little function to plot dendrogram with branch label colored
plot_dend<- function(dend,...){
dend_labels<- dend %>% labels()
dend %>%
color_labels(col = mypal[as.numeric(as.factor(dend_labels))]) %>%
set("labels_cex", 0.7) %>%
plot(...)
}Tip: what is that ... in the function?
Adding
...to a function is a powerful technique because it allows you to accept any number of additional arguments. Unfortunately it comes with a big downside: any misspelled or extraneous arguments will be silently ignored. This package ellipsis provides tools for making … safer
single linkage:
- Can handle diverse shapes.
- Very sensitive to outliers or noise.
- Often results in unbalanced clusters.
- Extended, trailing clusters in which observations fused one at a time -chaining.
sing.hclust<- hclust(Dmat,method="single")
plot_dend(as.dendrogram(sing.hclust), main = "single linkage")
Average linkage:
- A compromise between single and complete linkage.
- Less sensitive to outliers.
- Works better with spherical distributions.
ave.hclust<- hclust(Dmat,method="average")
plot_dend(as.dendrogram(ave.hclust), main = "average linkage")
Ward’s linkage
Ward’s linkage merges the two clusters whose union increases the within-cluster sum of squares the least. It tends to give compact, similar-sized clusters. In R, use method = "ward.D2": the help page ?hclust says "ward.D" does not implement Ward’s criterion.
ward.hclust<- hclust(Dmat,method="ward.D2")
plot_dend(as.dendrogram(ward.hclust), main = " Ward linkage")
# cut the tree into 9 clusters
rect.hclust(ward.hclust, k = 9)
cl<- cutree(ward.hclust, k = 9)
table(type=colnames(X), clusters=cl)#> clusters
#> type 1 2 3 4 5 6 7 8 9
#> BREAST 2 0 1 0 0 0 0 2 2
#> CNS 5 0 0 0 0 0 0 0 0
#> COLON 0 0 0 0 0 0 7 0 0
#> K562A-repro 0 0 0 0 0 1 0 0 0
#> K562B-repro 0 0 0 0 0 1 0 0 0
#> LEUKEMIA 0 0 0 0 5 1 0 0 0
#> MCF7A-repro 0 0 0 0 0 0 0 1 0
#> MCF7D-repro 0 0 0 0 0 0 0 1 0
#> MELANOMA 1 0 0 0 0 0 0 0 7
#> NSCLC 2 0 1 6 0 0 0 0 0
#> OVARIAN 0 0 1 5 0 0 0 0 0
#> PROSTATE 0 0 0 2 0 0 0 0 0
#> RENAL 1 7 1 0 0 0 0 0 0
#> UNKNOWN 0 0 1 0 0 0 0 0 0
Complete linkage with different distances
Dmat<- dist(t(ncidat),method="manhattan") #L1 distance
com.hclust<- hclust(Dmat,method="complete")
plot_dend(as.dendrogram(com.hclust), main = " manhattan distance with Complete linkage")
We can try all different combinations of distance matrix and different linkages. One can also use 1- cor(X) as a distance measure! It is commonly used in the clustering of gene expression. Also, use either average linkage or Ward’s linkage.
Ward’s linkage for 1- cor(X) distance
cor calculate correlation between columns of a matrix. Do not need to transpose the matrix for calculating the distances between samples(columns).
Dmat<- as.dist(1-cor(ncidat))
ward.hclust<- hclust(Dmat,method="ward.D2")
plot_dend(as.dendrogram(ward.hclust), main = "ward linkage-1-cor(X) distance")
6.6 Sort dendrogram
The two branches from the same node can be flipped in the dendrogram and it does not affect the meaning of the cluster structure in the data. However, one can sort the dendrogram so it is easier to read.
Take a look at dendsort!
The subtrees in the resulting dendrogram are sorted based on the average distance of subtrees at every merging point. The tighter cluster, in other words the cluster with smaller average distance, is placed on the left side of branch. When a leaf merge with a cluster, the leaf is placed on the right side.
library(dendsort)
plot_dend(as.dendrogram(ward.hclust), main = "ward linkage-1-cor(X) distance")
plot_dend(as.dendrogram(ward.hclust) %>%
dendsort(),
main = "ward linkage-1-cor(X) distance sorted dendrogram")
6.7 Deep understanding of a heatmap
There are three main points I will stress on plotting a bi-clustered heatmap:
- scale your data (center/standardize your data or not).
- range of the data and color mapping.
- clustering. (which distance measure and linkage method to use).
You probably do not understand heatmap! Please read You probably don’t understand heatmaps by Mick Watson.
In the blog post, Mick used heatmap function in the stats package, I will try to walk you through comparing heatmap, and heatmap.2 from gplots package.
I want to start with this quote:
“The defaults of almost every heat map function in R does the hierarchical clustering first, then scales the rows then displays the image”.
In other words, the scale parameter inside the heatmap functions only plays a role in displaying the colors, but does not involve clustering. This is critical to know! We will test to see if this holds true.
Careful: this is true for heatmap() and heatmap.2(). pheatmap() is different: with scale = "row" it scales first and then clusters the scaled values. Run pheatmap(mat, cluster_cols = FALSE, scale = "row") on the matrix below and you will see h1 next to l1. Always check the help page of the function you use.
Let’s simulate a dummy data
library(stats)
library(gplots)
h1 <- c(10,20,10,20,10,20,10,20)
h2 <- c(20,10,20,10,20,10,20,10)
l1 <- c(1,3,1,3,1,3,1,3)
l2 <- c(3,1,3,1,3,1,3,1)
mat <- rbind(h1,h2,l1,l2)
par(mfrow =c(1,1), mar=c(4,4,1,1))
plot(1:8,rep(0,8), ylim=c(0,35), pch="", xlab="Time", ylab="Gene Expression")
for (i in 1:nrow(mat)) {
lines(1:8,mat[i,], lwd=3, col=i)
}
legend(1,35,rownames(mat), 1:4, cex=0.7)
In this dummy example, we have four genes (l1, l2, h1, h2) that are measured in 8 time points.
when we do clustering, we want to cluster l1 h1 together, and l2 h2 together as they have the same trend across the time points. However, you will notice that the scale of the expression levels of these four genes are different: with h1 and h2 are high, and l1 l2 are low.
If we calculate the distance:
dist(mat)#> h1 h2 l1
#> h2 28.284271
#> l1 38.470768 40.496913
#> l2 40.496913 38.470768 5.656854
## I will use the default for linkage method: complete
plot(hclust(dist(mat)))
The default distance measure is Euclidean distance, and you will see h1 and h2 are closer (28.284271), l1 and l2 are closer. This simply because of how euclidean distance is defined.
Let’s check the help for ?heatmap:
scale character indicating if the values should be centered and scaled in either the row direction or the column direction, or none. The default is “row” if symm false, and “none” otherwise.
symm logical indicating if x should be treated symmetrically; can only be true when x is a square matrix.
So the default is scale row inside the heatmap.
## default, I will give parameters explicitly
heatmap(mat, Colv=NA, col=greenred(10), scale = "row")
We do see h1,h2 cluster together; l1 l2 cluster together. Inside heatmap function, the default distance measure is the same as default of dist, the linkage method is the same as hclust.
If you read the heatmap carefully, you will find that h1,h2 are with large values, but they have the same red color as l1,l2. This confirms that heatmap() does clustering first, and then scales the row for representing the color!
How about if we turn off scale inside heatmap?
heatmap(mat, Colv = NA, col=greenred(10), scale = "none")
You will see the clustering does not change, but the color changed! l1 and l2 are all green now (small values)
How about if we scale the genes before we feed into heatmap? scale works on columns, transpose for rows.
mat.scaled<- t(scale(t(mat), center=TRUE, scale = TRUE))
mat.scaled#> [,1] [,2] [,3] [,4] [,5] [,6] [,7]
#> h1 -0.9354143 0.9354143 -0.9354143 0.9354143 -0.9354143 0.9354143 -0.9354143
#> h2 0.9354143 -0.9354143 0.9354143 -0.9354143 0.9354143 -0.9354143 0.9354143
#> l1 -0.9354143 0.9354143 -0.9354143 0.9354143 -0.9354143 0.9354143 -0.9354143
#> l2 0.9354143 -0.9354143 0.9354143 -0.9354143 0.9354143 -0.9354143 0.9354143
#> [,8]
#> h1 0.9354143
#> h2 -0.9354143
#> l1 0.9354143
#> l2 -0.9354143
#> attr(,"scaled:center")
#> h1 h2 l1 l2
#> 15 15 2 2
#> attr(,"scaled:scale")
#> h1 h2 l1 l2
#> 5.345225 5.345225 1.069045 1.069045
Let’s see how the distance change among genes:
dist(mat.scaled)#> h1 h2 l1
#> h2 5.291503
#> l1 0.000000 5.291503
#> l2 5.291503 0.000000 5.291503
plot(hclust(dist(mat.scaled)))
Wow! h1 and l1 are clustered together; l2 and h2 are clustered together.
heatmap(mat.scaled, Colv = NA, col=greenred(10), scale = "none")
I hope you understand now how scale the data before and after can affect the looking of your heatmaps.
If we do not scale the data beforehand, but we still want l1 and h1 cluster together; l2 and h2 cluster together, we can use a different distance measure.
## correlation among the genes
cor(t(mat))#> h1 h2 l1 l2
#> h1 1 -1 1 -1
#> h2 -1 1 -1 1
#> l1 1 -1 1 -1
#> l2 -1 1 -1 1
## 1- correlation to define the distance
1- cor(t(mat))#> h1 h2 l1 l2
#> h1 0 2 0 2
#> h2 2 0 2 0
#> l1 0 2 0 2
#> l2 2 0 2 0
hc <- hclust(as.dist(1-cor(t(mat))))
plot(hc)
Indeed, h1 and l1 are together; h2 and l2 are together.
Now, we plot the heatmap, but set scale = “none” inside heatmap
heatmap(mat, Colv = NA, Rowv=as.dendrogram(hc), col=greenred(10), scale = "none")
Is this what you expect?! Yes, l2 and h2 are clustered together; l1 and h1 are clustered together. but because the value range are different, you see l1 and l2 are green (small values); h1 and h2 are red (big values).
The magic will happen if we set scale =“row” which is the default:
heatmap(mat, Colv = NA, Rowv=as.dendrogram(hc), col=greenred(10), scale = "row")
I hope I have clarified a bit for the complications of heatmaps.
6.8 heatmap.2 function in gplots package
From the help page:
scale character indicating if the values should be centered and scaled in either the row direction or the column direction, or none. The default is “none”.
The default is none!!, no scaling.
Please also pay attention to the Color Key of the heatmap.
library(gplots)
## defaults of heatmap.2, scale is none
heatmap.2(mat, trace = "none", Colv= NA, dendrogram = "row", scale = "none")
## heatmap() and heatmap.2(): clustering first, then the scale argument only changes the colors (pheatmap scales first!)
heatmap.2(mat, trace = "none", Colv= NA, dendrogram = "row", scale = "row")
how about we scale the data explicitly first and use euclidean distance. works fine!
heatmap.2(t(scale(t(mat), center=TRUE, scale=TRUE)),
trace = "none", Colv= NA,
dendrogram = "row", scale = "none")
use 1- cor(x) as distance and do not scale before hand
heatmap.2(mat, trace = "none",
Colv= NA, dendrogram = "row",
scale = "none",
hclust=function(x) hclust(x, method='complete'),
distfun=function(x) as.dist(1-cor(t(x))))
use 1- cor(x) as distance and do not scale before hand, but use scale in the heatmap.2 function to represent the colors
heatmap.2(mat, trace = "none",
Colv= NA, dendrogram = "row",
scale = "row",
hclust=function(x) hclust(x, method='complete'),
distfun=function(x) as.dist(1-cor(t(x))))
scale before hand and use 1- cor(x) as distance
heatmap.2(t(scale(t(mat), center=TRUE, scale=TRUE)), trace = "none",
Colv= NA, dendrogram = "row",
hclust=function(x) hclust(x, method='complete'),
distfun=function(x) as.dist(1-cor(t(x))))
Note that the dendrogram can be rotated and without changing the clustering. Check dendsort if you want to specify the order of the dendrogram.
The ComplexHeatmap which now I am using mainly does not do any scaling inside the Heatmap function.
6.9 Color mapping for heatmap
Have a look at the documentation of ComplexHeatmap.
For heatmap visualization, colors are the major representation of the data matrix. In most cases, the heatmap visualizes a matrix with continuous numeric values. In this case, users should provide a color mapping function. A color mapping function should accept a vector of values and return a vector of corresponding colors. Users should always use
circlize::colorRamp2()function to generate the color mapping function inHeatmap(). The two arguments forcolorRamp2()is a vector of break values and a vector of corresponding colors.colorRamp2()linearly interpolates colors in every interval through LAB color space. Also usingcolorRamp2()helps to generate a legend with proper tick marks.
I literally took the example from the tutorial.
Let’s make a dummy matrix.
library(ComplexHeatmap)
set.seed(123)
nr1 = 4; nr2 = 8; nr3 = 6; nr = nr1 + nr2 + nr3
nc1 = 6; nc2 = 8; nc3 = 10; nc = nc1 + nc2 + nc3
mat = cbind(rbind(matrix(rnorm(nr1*nc1, mean = 1, sd = 0.5), nr = nr1),
matrix(rnorm(nr2*nc1, mean = 0, sd = 0.5), nr = nr2),
matrix(rnorm(nr3*nc1, mean = 0, sd = 0.5), nr = nr3)),
rbind(matrix(rnorm(nr1*nc2, mean = 0, sd = 0.5), nr = nr1),
matrix(rnorm(nr2*nc2, mean = 1, sd = 0.5), nr = nr2),
matrix(rnorm(nr3*nc2, mean = 0, sd = 0.5), nr = nr3)),
rbind(matrix(rnorm(nr1*nc3, mean = 0.5, sd = 0.5), nr = nr1),
matrix(rnorm(nr2*nc3, mean = 0.5, sd = 0.5), nr = nr2),
matrix(rnorm(nr3*nc3, mean = 1, sd = 0.5), nr = nr3))
)
mat = mat[sample(nr, nr), sample(nc, nc)] # random shuffle rows and columns
rownames(mat) = paste0("row", seq_len(nr))
colnames(mat) = paste0("column", seq_len(nc))In following example, values between -2 and 2 are linearly interpolated to get corresponding colors, values larger than 2 are all mapped to red and values less than -2 are all mapped to green.
library(circlize)
col_fun<- colorRamp2(c(-2, 0, 2), c("green", "white", "red"))
#col_fun(seq(-3, 3))
Heatmap(mat, name = "mat", col = col_fun)
As you can see, the color mapping function exactly maps negative values to green and positive values to red, even when the distribution of negative values and positive values are not centric to zero. Also this color mapping function is not affected by outliers. In following plot, the clustering is heavily affected by the outlier (see the dendrogram) but not the color mapping.
mat2<- mat
mat2[1, 1] = 100000
Heatmap(mat2, name = "mat", col = col_fun,
column_title = "a matrix with outliers")
More importantly, colorRamp2() makes colors in multiple heatmaps comparable if they are set with a same color mapping function. In following three heatmaps, a same color always corresponds to a same value.
Heatmap(mat, name = "mat", col = col_fun, column_title = "mat")
Heatmap(mat/4, name = "mat", col = col_fun, column_title = "mat/4")
Heatmap(abs(mat), name = "mat", col = col_fun, column_title = "abs(mat)")
6.10 Rastering
“Seeing is believing”. Yet, your eyes may trick you.
When you have too many columns or rows (e.g, > 10,000), the use_raster option really helps. Also consider downsample the matrix to a smaller number of dimension for plotting the heatmap. Your screen resolution is not as high as 300,000 pixels if you have 300,000 cells (columns).
In this blog post Plotting heatmaps from big matrices in R:
if we have a 50 column-matrix with one line per gene (~20,000 lines), then there are likely more lines in this matrix than pixels in your screen - 1080 vertical pixels in an HD screen (unless you’re reading this in a fancy future of hyper high definition).
The problem with plotting matrix that have more lines than pixels in the screen is precisely that: each pixel will have to represent several values from the matrix. R’s default behaviour in that case might not be optimal for what we intend to show.
Please also read https://jokergoo.github.io/2020/06/30/rasterization-in-complexheatmap/ In fact, I asked to have the raster option back in 2016 :) https://github.com/jokergoo/ComplexHeatmap/issues/29.
6.11 Why the differential gene expression heatmap looks so good?
Because you selected the genes by differential expression analysis using tools such as DESeq2 and when you plot only those genes, the heatmap will look perfect (as expected). You picked the genes because they differ between the groups, so of course the heatmap separates the groups. It is not evidence of anything. Don’t use it as validation.
6.12 Take home message
Generate a heatmap is easy, but make sure to understand the parameters in each heatmap function.
Understand your data and what you are looking for. Do you need to scale your data before clustering?
distance measure and linkage method can drastically affect your clustering. Choose the right one for your data!
Understand the color mapping.
6.13 Further readings
Assessing clustering significance withsigclust2
A real example for ComplexHeatmap using genomics data by Kevin: https://github.com/kevinblighe/E-MTAB-6141
Unsupervised learning course material from Summer Institute in Statistics for Big Data (SISBID) https://github.com/SISBID/Unsupervised-Learning