首页 > 解决方案 > 从使用 dendextend 生成的树状图中删除标签

问题描述

这是一个类似的问题,但不完全相同,因为我想用dendextend 来做这个。我的问题是我的一些标签名称很长,我想删除它们。我已经尝试了一些技术。

  1. 我尝试更改 cex = 0
  2. 我尝试将颜色更改为白色,但这只是隐藏标签,而且当名称很长时仍然是一个问题。
  3. 我尝试绘制标签 =F ,但这也不起作用。反正有没有完全消除标签?这是一个示例代码。
dend <- USArrests[1:5, ] %>%
  dist() %>%
  hclust() %>%
  as.dendrogram()

dend = dend%>% set("labels_cex", 0) %>% set("labels_col", "white") # change to white however this does not work well because the color bars would just get pushed out

dend = dend%>% set("labels_cex", 0) %>% set("labels_col", "black") # setting cex to 0 does nothing


plot(dend, labels=FALSE ) # labels =F are ignore 
colored_bars(colors = cbind ( 
  state= "red" ))

在此处输入图像描述

标签: r

解决方案


您可以使用 dendrapply 更改或删除叶节点的标签属性:

suppressPackageStartupMessages(invisible(
  lapply(c("dendextend", "dplyr"),
           require, character.only = TRUE)))  
dend <- USArrests[1:5, ] %>%
    dist() %>%
    hclust() %>%
    as.dendrogram()
  
noLabel <- function(x) {
  if (stats::is.leaf(x)) {
    attr(x, "label") <- NULL }
  return(x)
}
plot(stats::dendrapply(dend, noLabel))
colored_bars(colors = cbind (state= "red" ))

reprex 包(v0.3.0)于 2020 年 8 月 5 日创建

编辑

作为替代方案,您始终可以截断行名和/或在图中留出一些空间并将条形向下移动:

suppressPackageStartupMessages(invisible(
  lapply(c("dendextend", "dplyr", "stringr"),
           require, character.only = TRUE)))  
oldpar <- par()
par(mar=c(8,4,4,2))
dend <- data.frame(USArrests[1:5, ], 
  row.names = str_trunc(rownames(USArrests[1:5, ]), 8, ellipsis="..")) %>%
    dist() %>%
    hclust() %>%
    as.dendrogram() %>% plot()
colored_bars(colors = cbind (state= "red" ), y_shift = -60)

par(mar=oldpar$mar)

reprex 包(v0.3.0)于 2020 年 8 月 5 日创建


推荐阅读