I am unable to pass other color schemes into rect_border but it somehow works when the colour palette lancet is specified. How can I adjust the second plot to work on the smooth_rainbow colours?
See reprex below:
library(factoextra)
library(ggplot2)
library(khroma)
df <- scale(mtcars) # Standardize the data
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()
#> Warning: `guides(<scale> = FALSE)` is deprecated. Please use `guides(<scale> =
#> "none")` instead.
p$layers[[1]]$data$col[p$layers[[1]]$data$col == "black"] <- "white"
p$layers[[2]]$data$angle <- 0
p

smooth_rainbow <- khroma::colour("smooth rainbow")
p2 <-
fviz_dend(hc, k = 4, # Cut in four groups
cex = 0.6, # label size
k_colors = smooth_rainbow(n = 4),
color_labels_by_k = TRUE, # color labels by groups
rect = TRUE, # Add rectangle around groups
rect_border = smooth_rainbow(n = 4),
rect_fill = TRUE,
rotate = TRUE) +
ggplot2::theme_dark()
#> Warning: `guides(<scale> = FALSE)` is deprecated. Please use `guides(<scale> =
#> "none")` instead.
#> Error in if (color == "cluster") color <- "default": the condition has length > 1
p2
#> Error in eval(expr, envir, enclos): object 'p2' not found
Created on 2023-05-07 by the reprex package (v2.0.1)
> sessionInfo()
R version 4.2.3 (2023-03-15 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 19044)
Matrix products: default
locale:
[1] LC_COLLATE=English_South Africa.utf8 LC_CTYPE=English_South Africa.utf8
[3] LC_MONETARY=English_South Africa.utf8 LC_NUMERIC=C
[5] LC_TIME=English_South Africa.utf8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] khroma_1.10.0 cluster_2.1.4 MTGmeta_0.0.0.9000 factoextra_1.0.7
[5] magrittr_2.0.3 here_1.0.1 forcats_0.5.1 stringr_1.4.0
[9] dplyr_1.0.9 purrr_0.3.5 readr_2.1.2 tidyr_1.2.0
[13] tibble_3.1.8 ggplot2_3.3.6 tidyverse_1.3.2
This is a bug and it would be great if you could report it to the package maintainer. The error originates from a conditional statement in
factoextra:::.rect_dendrogram, which tests if your color argument iscolor == "cluster". This only works if your color argument is a vector of length 1. (e.g., passing a palette name works, as you have demonstrated).When passing a vector of colors, this naturally fails, as R doesn't like to compare vectors of length > 1 with a
==. If you replace the conditional statement, e.g. withall(color == "cluster"), it works.NB I have copied the adjusted functions for your convenience - there are a few uncommented modifications, in particular adding required
factoextra:::to some un-exported functions.Created on 2023-05-07 with reprex v2.0.2