Search code examples
rggplot2cluster-analysis

Adjusting output in fviz_cluster


I would like to change the results of my fviz_clust plot. Specifically, change the legend to say "Cluster" instead of "cluster", but also remove the curly lines found within the legend (I think they are letters, but not entirely sure).

I know fviz_cluster works with other elements in ggplot. Therefore my first thought was to change the legend title within each scale_..._.. of my plot, but that still resulted in the original legend displaying. Secondly, I thought I could introduce a scale_shape_manual() object to ggplot but the plot ignored it.

Code:

km.res <- kmeans(iris[,-5], 3)
p <- fviz_cluster(km.res, iris[,-5]) +
scale_color_brewer(palette='Set2') + # set guides=FALSE to remove legend
scale_fill_brewer(palette='Set2') +
scale_shape_manual('1'=22,'2'=23,'3'=24) # plot ignores this
ggtitle(label='')
p

Ideally I would like to show a very similar legend to what fviz_cluster produces, but with the shape and box of color around each shape in the legend. And finally with the title of "Cluster."


Solution

  • fviz_cluster works with ggplot, you had an error in the code that caused changes to not be rendered properly.

    With regards to changing the title to "Cluster", you can do this within scales-..._... or guides. Specify the new shape values in scale_shape_manual.

    library(factoextra)
    km.res <- kmeans(iris[, -5], 3)
    
    p <- fviz_cluster(km.res, iris[, -5]) +
      scale_color_brewer('Cluster', palette='Set2') + 
      scale_fill_brewer('Cluster', palette='Set2') +
      scale_shape_manual('Cluster', values=c(22,23,24)) + 
      ggtitle(label='') 
    p
    

    enter image description here

    Removing the text label annotation in the legend can usually be done by specifying geom_text(show.legend = F). I could not do this directly so instead I plot only the points in fviz_cluster, and then add the geom_text after by making use of the data structure produced by fviz_cluster.

    p2 <- fviz_cluster(km.res, iris[, -5], geom = c("point")) +
      scale_color_brewer('Cluster', palette='Set2') + 
      scale_fill_brewer('Cluster', palette='Set2') +
      scale_shape_manual('Cluster', values=c(22,23,24)) + 
      ggtitle(label='') 
    p2 + geom_text(data=p2$data, aes(x=x, y=y, label=name, colour=cluster),
      vjust=-1, show.legend = F)
    

    enter image description here