将表行添加到树状图标签

时间:2018-08-23 17:07:22

标签: r dendrogram hclust dendextend

我实质上是在尝试将树状图的标签更改为表中的相应行。例如,考虑USArrest数据集。

现在,树状图上的标签只是州名称“阿拉巴马州”,依此类推。但是看着数据表,阿拉巴马州的行看起来像这样

        Murder Assault UrbanPop Rape
Alabama   13.2     236       58 21.2

因此,我不仅希望将“阿拉巴马州”(Alabama)用作标签,还希望有完整的一行:Alabama 13.2 236 58 21.2,依此类推,对于所有其他树状图标签。

我的代码如下:

library("ggplot2")
library("ggdendro")
library(dendextend)
data(USArrests)

dend <- USArrests %>%  scale %>% 
dist %>% hclust %>% as.dendrogram
dend %>% plot
dend %>% set("labels_cex", 0.8) %>% # Change size
plot(main = "Dendrogram") # plot

我试图将树状图减少到仅两个分支,以使对我来说更容易。假设我正在使用dend <- USArrests[1:2,] %>% scale %>%

我尝试过这样的事情:

alabama_label <- USArrests[1,]
alaska_label <- USArrests[2,]
dend %>% set("labels", c(alabama_label, alaska_label))

但是那没有用。它只给了我USArrests[1,1]USArrests[2,1]作为标签的值。

所以我只是想知道,我怎么可能在所有行上标记树状图?

1 个答案:

答案 0 :(得分:0)

去那里:

# library("ggplot2")
## library("ggdendro") ## this package is not relevant for your question. (and in general it is mostly deprecated compared with the features from dendextend)


library(dendextend)
data(USArrests)

dend <- USArrests %>%  scale %>% 
        dist %>% hclust %>% as.dendrogram %>% 
        set("labels_cex", 0.75) # Change size

USArrests_dend_order <- USArrests[order.dendrogram(dend), ]
new_labels <- paste(rownames(USArrests_dend_order), apply(USArrests_dend_order,1,paste,collapse="_"))

dend2 <- dend
labels(dend2) <- new_labels # the labels assignment function is from dendextend


par(mfrow = c(1,2), mar = c(2,0,0,4))
plot(dend, horiz = T)
par(mar = c(2,0,0,10))
plot(dend2, horiz = T)

输出返回带有正确标签的树状图,并添加您要添加​​的内容:

enter image description here