Search code examples
rggplot2ggplotlyggdendro

ggplotly() of a ggdendro object: labels in tooltip


Given the example in https://plotly.com/ggplot2/dendrogram/

library(plotly)
library(ggplot2)
library(ggdendro)
hc <- hclust(dist(USArrests), "ave")
p <- ggdendrogram(hc, rotate = FALSE, size = 2)
ggplotly(p)

How can I display the labels within the tooltip when hoovering over the bottom of the graphic? I have many individuals and the text labels are inconvenient. Also regarding classes, how would I do the equivalent to:

cl <- cutree(hc,5)
plot(hc,labels=cl)

Solution

  • To show the state name or the labels in the tooltip when covering over the leafs of your dendrogram you could add an (in)visible geom_point to whose tooltip you can add the labels via the text attribute. To this end we first have to get the leaf positions and labels using dendro_data(). And to use the results from cutree() for the leaf labels you could overwrite the default x scale using the values from cutree() for the labels, where we have to make sure that we pass them in the right order.

    library(plotly)
    library(ggplot2)
    library(ggdendro)
    hc <- hclust(dist(USArrests), "ave")
    cl <- cutree(hc, 5)
    
    labels_x <- cl[hc$order]
    dat <- dendro_data(hc)$labels
    
    p <- ggdendrogram(hc, rotate = FALSE, size = 2) +
      geom_point(data = dat, aes(x = x, y = y, text = label)) +
      scale_x_continuous(breaks = seq_along(labels_x), labels = labels_x)
    
    ggplotly(p)
    

    enter image description here