ggdendro图的颜色标签

时间:2019-02-10 12:46:43

标签: r

我正在尝试应用dendextend以便为ggdendro标签着色。我收到此错误:

Error in UseMethod("as.dendrogram") : 
  no applicable method for 'as.dendrogram' applied to an object of class "dendro"

为什么转换无效?知道如何解决吗?

代码:

library(IncDTW)
library(ggplot2)
library(ggdendro) 
library(dendextend)

A <- matrix(1:50, nrow = 50, ncol = 1)
B <- matrix(1:75, nrow = 75, ncol = 1)
C <- matrix(25:49, nrow = 25, ncol = 1)
D <- matrix(1:50, nrow = 50, ncol = 1)
treeList <- list(A,B,C,D)

names(treeList)[1] <- "A"
names(treeList)[2] <- "B"
names(treeList)[3] <- "C"
names(treeList)[4] <- "D"

result <- dtw_dismat(treeList, dist_method = "norm2", return_matrix = F)
distMatrixResult <- result$dismat
hc <- hclust(distMatrixResult, method = "average")
hc <- dendro_data(hc)
dict <- setNames(names(treeList), 1:length(names(treeList)))
hc$labels$label <- sapply(hc$labels$label, function(x) dict[[as.character(x)]])
ggdendrogram(hc, rotate = TRUE, theme_dendro = FALSE)
dend <- as.dendrogram(hc)
d5=color_branches(dend)
plot(d5)
d5g=color_branches(dend,5,groupLabels=TRUE)
plot(d5g)
d5gr=color_branches(dend,5,groupLabels=as.roman)
plot(d5gr)

2 个答案:

答案 0 :(得分:1)

似乎您将树状图与树状图数据混淆了。这将起作用:

dend <- as.dendrogram(hc)

dict <- setNames(names(treeList), 1:length(names(treeList)))
hc$labels$label <- sapply(hc$labels$label, function(x) dict[[as.character(x)]])
ggdendrogram(dend, rotate = TRUE, theme_dendro = FALSE)

d5=color_branches(dend)
plot(d5)
d5g=color_branches(dend,4,groupLabels=TRUE)
plot(d5g)
d5gr=color_branches(dend,4,groupLabels=as.roman)
plot(d5gr)

结果:

enter image description here

编辑:

作为@maxatSOflow pointed out,我们可以使用usedist::dist_setNames()将名称设置为"dist"对象。因此,要最终使树状图标记为预期的,可以执行以下操作。

library(IncDTW)
result <- dtw_dismat(treeList, dist_method="norm2", return_matrix=FALSE)
distMatrixResult <- result$dismat

# install.packages("usedist")
library(usedist)
distMatrixResult <- dist_setNames(distMatrixResult, LETTERS[1:4])

hc <- hclust(distMatrixResult, method="average")

library(ggdendro) 
ggdendrogram(hc, rotate=TRUE, theme_dendro=FALSE)
dend <- as.dendrogram(hc)


library(dendextend)
d5=color_branches(dend)
plot(d5)
d5g=color_branches(dend,4,groupLabels=TRUE)
plot(d5g)
d5gr=color_branches(dend,4,groupLabels=as.roman)
plot(d5gr)

给予:

enter image description here

数据:

A <- matrix(1:50, nrow=50, ncol=1)
B <- matrix(1:75, nrow=75, ncol=1)
C <- matrix(25:49, nrow=25, ncol=1)
D <- matrix(1:50, nrow=50, ncol=1)

treeList <- setNames(list(A, B, C, D), LETTERS[1:4])

答案 1 :(得分:1)

在当前版本的IncDTW中,您需要在使用dtw_dismat()之后添加名称,在将来的版本中,我将对其进行调整。因此,现在尝试:

result <- dtw_dismat(treeList, dist_method = "norm2", return_matrix = TRUE)
distMatrixResult <- result$dismat
dnames <- LETTERS[1:4]
dimnames(distMatrixResult) <- list(dnames , dnames)
distMatrixResult <- as.dist(distMatrixResult)

也可以看看这篇文章: ggdendrogram labels