1
votes

heatmap.2 assigns incorrect colors to labels when using "colRow" argument. Is there an alternative way how to assign colors to labels in heatmap.2? Or am I doing something wrong? (examples are based on examples from Label and color leaf dendrogram and How to color the branches and tick labels in the heatmap.2?)

library(dendextend)
library(gplots)

#make dataset
sample = data.frame(matrix(floor(abs(rnorm(20000)*100)),ncol=1000))
groupCodes <- c(rep("Cont",5), rep("Tre1",5), rep("Tre2",5), rep("Tre3",5))
rownames(sample) <- make.unique(groupCodes)
colorCodes <- c(Cont="red", Tre1="green", Tre2="blue", Tre3="yellow")

#calculate distances, cluster
distSamples <- dist(sample)
hc <- hclust(distSamples)
dend <- as.dendrogram(hc)

# Assign the labels of dendrogram object with new colors:
labels_colors(dend) <- colorCodes[groupCodes][order.dendrogram(dend)]
col_labels<-labels_colors(dend)

# plot dendrogram
plot(dend,main ="colors of labels OK")

# plot dendogram and heatmap with heatmap.2
sample.datamatrix<-data.matrix(sample)
heatmap.2(sample.datamatrix, scale="row", 
          trace="none", 
          dendrogram="row",
          colRow = col_labels, # to add colored labels
          Rowv = dend, 
          main="colors of labels mixed-up",
          labCol = FALSE) # hide column names (i.e. gene names)

enter image description here

1

1 Answers

1
votes

ash, you need to keep col_labels in the original order of the data.

Here is the modified code: (find the "WHAT I CHANGED" comment)

library(dendextend)
library(gplots)

#make dataset
sample = data.frame(matrix(floor(abs(rnorm(20000)*100)),ncol=1000))
groupCodes <- c(rep("Cont",5), rep("Tre1",5), rep("Tre2",5), rep("Tre3",5))
rownames(sample) <- make.unique(groupCodes)
colorCodes <- c(Cont="red", Tre1="green", Tre2="blue", Tre3="yellow")

#calculate distances, cluster
distSamples <- dist(sample)
hc <- hclust(distSamples)
dend <- as.dendrogram(hc)

# Assign the labels of dendrogram object with new colors:
labels_colors(dend) <- colorCodes[groupCodes][order.dendrogram(dend)]
col_labels<-labels_colors(dend)

# plot dendrogram
plot(dend,main ="colors of labels OK")

# <================= WHAT I CHANGED ===================>
# The labels need to be in the order of the original data:
col_labels <- colorCodes[groupCodes]
# </================= WHAT I CHANGED ===================>

# plot dendogram and heatmap with heatmap.2
sample.datamatrix<-data.matrix(sample)
heatmap.2(sample.datamatrix, scale="row", 
          trace="none", 
          dendrogram="row",
          colRow = col_labels, # to add colored labels
          Rowv = dend, 
          main="colors of labels mixed-up",
          labCol = FALSE) # hide column names (i.e. gene names)

enter image description here