2

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?

jammah
  • 25
  • 5
  • You're mixing two packages here. The ggdendeo package is superseded by the dendextend package. Also, the rect.dendrogram function is for base R plots. It doesn't support ggplot2. – Tal Galili May 08 '21 at 14:50
  • Also, csin is not a dendrogram, it's an hclust object. – Tal Galili May 08 '21 at 14:56

1 Answers1

1

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

Tal Galili
  • 24,605
  • 44
  • 129
  • 187
  • Since the question was specifically about `ggdendro` package, any thoughts on drawing cluster rectangles in ggplot? – perechen Feb 15 '23 at 11:41
  • 1
    Sorry but it is not implemented. If someone wants to work on it I'd be happy to add it to dendextend – Tal Galili Apr 19 '23 at 03:47