rdendextendggdendro

ggdendrogram : adding colored rectangles for each cluster


I am not able to add colored rectangles around the chosen clusters.

   library(lattice)
   library(permute)
   library(vegan)
   library("ggplot2")
   library("ggdendro")
   library("dendextend")
   data(dune)
   d <- vegdist(dune)
   csin <- hclust(d, method = "aver")
   ggdendrogram(csin)
   rect.dendrogram(csin, 3, border = 1:3)

I get this answer: "Error in rect.dendrogram(csin, 3, border = 1:3) : x is not a dendrogram object." Although csin is the dendrogram object. Does anyone have a clue?


Solution

  • As I wrote in the comments:

    1. csin is hclust and not a dendrogram (use as.dendrogram to make it into a dendrogram)
    2. rect.dendrogram works with base R plots, not ggplot2.

    Here is a simple example of making your rect.dendrogram work:

    library("dendextend")
    d <- dist(iris[,-5])
    csin <- as.dendrogram(hclust(d, method = "aver"))
    plot(csin)
    rect.dendrogram(csin, 3, border = 1:3)
    

    The output:

    enter image description here