Factoextra:如何在 fviz_silhouette 函数中更改平均轮廓宽度的颜色?

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

我很好奇在 fviz_silhouette 函数中如何覆盖平均轮廓宽度的默认红色虚线的颜色值。刚刚看了下fviz_silhouette代码,百思不得其解,为什么作者固定行颜色参数? (从函数源代码中列出。)

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, ...)

并且 palette = "grey" 和 + theme_bw() 的结果仍然保留红色虚线,如下图所示。

您可以通过

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

先画图(默认红色线):

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

现在将颜色更改为黑色:

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