使用来自 factoextra 的 fviz_dend 和 ggplotly 时在悬停时显示点标签

Show point labels on hover when using fviz_dend from factoextra with ggplotly

我可以使用以下内容生成一个 plotly 树:

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 中的标签。目前悬停只显示坐标和色码:

我不经常使用 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

注意:矩形树创建的具体层数与上述有所不同,因此系统发育树的解决方案不能直接应用。但我假设您的用例是针对系统发育的。