当使用来自带有ggplotly的factoextra的fviz_dend时,在悬停时显示点标签

时间:2018-12-23 23:58:16

标签: r ggplot2 plotly ggplotly

我可以使用以下内容生成一个可绘制的树:

library(factoextra)
library(plotly)

hcl <- hclust(
  dist(mtcars, method = "euclidean"), 
  method = "complete")

ggplotly(
  fviz_dend(
    hcl, 
    k = 5,
    show_labels = FALSE,
    type = "phylogenic",
    phylo_layout = "layout_as_tree"
  )
)

fviz_dend有一个显示标签的选项,但是当有数百个点时,这变得很难看。相反,我希望能够将鼠标悬停在该点上并查看存储在hcl$labels中的标签。目前,悬停仅显示坐标和颜色代码:

See image

1 个答案:

答案 0 :(得分:1)

我不经常使用plotly软件包,希望有人会提供更好的解决方案,但以下工作(无论如何在我的机器上)都适用于系统树:

k = 5 # change this based on number of groups for cutting the tree

gp <- ggplotly(
  fviz_dend(
    hcl, 
    k = k,
    show_labels = TRUE, # leave this as the default TRUE, so that the labels
                        # are passed to the plotly object; we can remove them 
                        # in the next step.
    type = "phylogenic",
    phylo_layout = "layout_as_tree")
)

# remove hover text for line segments
gp$x$data[[1]]$text <- NA 

# for each group, assign the label's text value to the point's text value,
# then remove the label
for(i in seq(k, 1)){
  gp$x$data[[i+1]]$text <- gp$x$data[[i+1+k]]$text
  gp$x$data[[i + 1 + k]] <- NULL
}

gp

screenshot

注意:矩形树创建的特定层数与上面显示的有所不同,因此系统树的解决方案将无法直接应用。但是我认为您的用例是系统发育的。