如何使用预定义的样本组使用dendextend和heatmap.2为树状图标签着色

时间:2018-07-03 18:46:05

标签: r colors dendrogram gplots dendextend

heatmap.2使用“ colRow”参数时会为标签分配不正确的颜色。是否有其他方法可以为heatmap.2中的标签分配颜色?还是我做错了什么? (示例基于Label and color leaf dendrogramHow 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 个答案:

答案 0 :(得分:1)

灰,您需要按数据的原始顺序保留col_labels

这是修改后的代码:(找到“我更改了”注释)

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