ggdendrogram标签

时间:2019-02-08 13:05:38

标签: r

如何将树状图的标签更改为列表中与之匹配的名称?目前,我只获得列表号。

代码:

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

A <- matrix(1:50, nrow = 50, ncol = 1)
B <- matrix(1:100, 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")
ggdendrogram(hc)

2 个答案:

答案 0 :(得分:1)

dtw_distmat函数之后,您正在失去标签:

$dismat
         1    2        3        4
1 0.000000 2.60 4.013333 0.000000
2 2.600000 0.00 6.510000 2.600000
3 4.013333 6.51 0.000000 4.013333
4 0.000000 2.60 4.013333 0.000000

您可以使用hclust函数来转换dendro_data的输出。然后,您可以更改此变换后的对象的标签:

hc <- dendro_data(hc)
dict <- setNames(c('A', 'B', 'C', 'D'), 1:4)
hc$labels$label <- sapply(hc$labels$label, function(x) dict[[as.character(x)]])

ggdendrogram(hc)之后将返回带有标签的图。

答案 1 :(得分:1)

感谢您向我介绍此新功能。我会在 IncDTW 的下一版本中考虑它。同时,快速解决方案是执行以下操作:

a <- matrix(1:9, 3, 3)
a <- a + t(a)
as.dist(a)
b <- usedist::dist_setNames(a, letters[1:3])
b

# where dist_setnames() does the following:
dm <- as.matrix(d)
dimnames(dm) <- list(nm, nm)
stats::as.dist(dm)

因此dist_setnames()将dist.object转换为矩阵,这对于较小的时间序列列表来说很好,但是如果距离矩阵变大,则可能会出现问题。