Search code examples
rcluster-analysis

Factoextra: How to change color of the average silhouette width in the fviz_silhouette function?


I'm very curious about the ways to override the color value of the default red dashed line for average silhouette width in the fviz_silhouette function. Just peeked the fviz_silhouette code, and it puzzling me, why the author fixed line color parameter? (Listing from the function source code.)

p <- ggplot(df, mapping) + geom_bar(stat = "identity") + labs(y = "Silhouette width Si", x = "", title = paste0("Clusters silhouette plot ", 
            "\n Average silhouette width: ", round(mean(df$sil_width), 
                2))) + ggplot2::ylim(c(NA, 1)) + geom_hline(yintercept = mean(df$sil_width), 
        linetype = "dashed", color = "red")
    p <- ggpubr::ggpar(p, ...)

And the result with palette = "grey" and + theme_bw(), still preserves red dashed line, as in the image bellow. enter image description here


Solution

  • You can edit the color via

    p$layers[[2]]$aes_params$colour <- "black" # or whatever color you like
    

    To demonstrate first make a plot (with the default red color line):

    library(factoextra)
    library(cluster)
    data("iris")
    
    iris.scaled <- scale(iris[, -5])
    
    km.res <- kmeans(iris.scaled, 3, nstart = 2)
    
    sil <- silhouette(km.res$cluster, dist(iris.scaled))
    p <- fviz_silhouette(sil)
    p
    

    enter image description here

    Now change the color to black:

    p$layers[[2]]$aes_params$colour <- "black"
    p
    

    enter image description here