Add hoover text to a dendrogram with ggplotly

33 Views Asked by At

I would like to add a hoover text to a dendrogram with ggploty that appears when the cursor is placed on the axis labels. The displayed information should be the corresponding values of variables that were used for clustering.

I have tried doing this with layout(annotations = hover_annotations), as well as using plotly() directly but I am not able to get it to work. My issue is that I don't seem to be able to identify the correct coordinates of the axis labels for the dendrogram.

What I am looking for is something like this:

enter image description here

Here is a minimal example of a dendrogram that I would like to modify:

# Load required libraries
library(cluster)  # For clustering
library(ggplot2)  # For visualization

# Example data 
my_data <-  data.frame(
  Name = rep(c("Name1", "Name2", "Name3", "Name4", "Name5", "Name6", "Name7", "Name8", "Name9", "Name10"), times = 1),
  Var1 = rep(c(1, 2, 3, 4, 5), times = 10),
  Var2 = rep(c(20, 25, 50, 90,100), times = 10)
)

# Extract features for clustering
features <- my_data[, c("Var1", "Var2")]

# Compute distance matrix
distance_matrix <- dist(features)  

# Perform hierarchical clustering
hierarchical_result <- hclust(distance_matrix)


# Custom function to create x axis labels labels for the dendrogram
create_x_labels <- function(hc, data) {
  labels <- data$Name[hc$order]
  return(labels)
}

# Create the dendrogram plot using ggdendro
dendrogram_labels <- create_x_labels(hierarchical_result, my_data)
dendro <- as.dendrogram(hierarchical_result)
dendro <- dendro %>% set("labels", value = dendrogram_labels)  # Set the labels

# Convert the dendrogram plot to a ggplot object
dendro_plot <- ggdendro::ggdendrogram(dendro, rotate = FALSE)

# Convert the ggplot dendrogram to a plotly interactive plot
p <- ggplotly(dendro_plot, tooltip="label") %>%
  layout(
    xaxis = list(title = "ID", ticktext = dendrogram_labels),
    yaxis = list(title = "Distance")
  )

p

Any suggestions of how to solve this issue are much appreciated!

0

There are 0 best solutions below