Rotating labels within a dendrogram object and changing the default dendrogram colour (R)

258 views Asked by At

I am hoping to accomplish two things.

  1. I want to be able to rotate the labels. The fviz_dend function is compatible with ggplot2 theme function but I am not entirely sure how to accomplish it.

  2. I would like to change the line colour of the dendrogram - specifically those that do not fall within the clustering. I would like to change the black to white.

Any idea how to accomplish it on this reprex?

df <- scale(mtcars) # Standardize the data

library("factoextra")
library("cluster")

dist <- dist(df, method = "euclidean") # df = standardized data
hc <- hclust(dist, method = "ward.D2")

fviz_dend(hc, k = 4, # Cut in four groups
          cex = 0.6, # label size
          k_colors = "lancet",
          color_labels_by_k = TRUE, # color labels by groups
          rect = TRUE, # Add rectangle around groups
          rect_border = "lancet",
          rect_fill = TRUE,
          rotate = TRUE) +
ggplot2::theme_dark()
#> Warning: `guides(<scale> = FALSE)` is deprecated. Please use `guides(<scale> =
#> "none")` instead.

Created on 2022-03-13 by the reprex package (v2.0.0)

1

There are 1 answers

1
Allan Cameron On BEST ANSWER

From looking at the docs, I don't see a way to do this directly, but since this is a ggplot object, you can rewrite the layer data after creating the object.

df <- scale(mtcars) # Standardize the data

library("factoextra")
library("cluster")
library(ggplot2)

dist <- dist(df, method = "euclidean") # df = standardized data
hc <- hclust(dist, method = "ward.D2")

p <- fviz_dend(hc, k = 4, # Cut in four groups
          cex = 0.6, # label size
          k_colors = "lancet",
          color_labels_by_k = TRUE, # color labels by groups
          rect = TRUE, # Add rectangle around groups
          rect_border = "lancet",
          rect_fill = TRUE,
          rotate = TRUE) +
          theme_dark()

p$layers[[1]]$data$col[p$layers[[1]]$data$col == "black"] <- "white"
p$layers[[2]]$data$angle <- 0
p

enter image description here