Adjusting output in fviz_cluster
Asked Answered
P

1

6

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."

Prang answered 1/12, 2018 at 14:59 Comment(3)
Hard to say without a reproducible example. But running the Iris example from fviz_cluster I'm able to change these things the same as any other ggplot. Your question doesn't include what you've done to try changing the legend or shapeEwaewald
Sorry about not using iris. But my question does include what I've done to change the legend and shape.Prang
You can remove legends with theme(legend.position = "none"). Take a look at the docs for setting manual scales, such as shape: you supply 1 vector to the argument valuesEwaewald
P
8

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

Pish answered 4/12, 2018 at 16:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.