Search code examples
rplotcluster-analysis

Increase font size while using fviz_nbclust?


I'm trying to increase the font/label size of a plot I am making using fviz_nbclust. I tried looking up all sorts of combinations of "fviz_nbclust", "size", "font", "increase", but didn't turn up anything.

I saw a suggestion on this post that worked when I was doing just plot() that it worked, but can't just be used with fviz_nbclust. I also checked the documentation for the package factoextra (here), but didn't really see anything on page 49/50 that I thought might help.

Here's my code:

set.seed(123)
wss <- function(k) {
       kmeans(datT, k, nstart = 10)$tot.withinss
       }
k.values <- 1:15
wss_values <- map_dbl(k.values, wss)

pdf("within_clus_sum1.pdf",width = 11, height = 8) 
plot(k.values, wss_values,
       type="b", pch = 19, frame = FALSE, 
       xlab="Number of clusters K",
       ylab="Total within-clusters sum of squares",
       cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5)

dev.off() 

pdf("within_clus_sum2.pdf",width = 11, height = 8) 
fviz_nbclust(datT, kmeans, method = "wss")
dev.off() 

As you can see I am just trying to get a feel for what the optimal number of clusters are as determined using the Elbow Method.

What I'm hoping to do is increase the title, label, and tick mark sizes in plots generated using fviz_nbclust because I am including in them a write-up, and if I put the plots in a row of two or three, they are near illegible. Any help any one could offer would be appreciated.


Solution

  • The factoextra package uses ggplot2 to generate the plots. This means you can alter the appearance of the plot using ggplot2 theming. For example:

    elbow.plot <- fviz_nbclust(datT, kmeans, method = "wss", k.max = 10, verbose = F, nboot = 100)
    # change size and color of title and x axis labels
    elbow.plot + theme(axis.text.x = element_text(size = 15, color = "red"), title = element_text(size = 15, color = "blue")
    

    You can learn more about ggplot2 for example here.

    If you want to change the color and size of the line I realized this is a bit trickier because actually the fviz_nbclust function calls a ggpubr fuction that is a wrapper for ggplot2 (it's as easy as that). And the only parameter that you easily can change is the line color:

    fviz_nbclust(datT, kmeans, method = "wss", k.max = 10, verbose = F, nboot = 100, linecolor = "red")
    

    To alter other parameters you can do the following:

    fviz_nbclust(datT, kmeans, method = "wss", k.max = 10, verbose = F, nboot = 100)  + 
    theme(axis.text.x = element_text(size = 15))  + 
    geom_line(aes(group = 1), color = "red", linetype = "dashed",size = 3) + 
    geom_point(group = 1, size = 5, color = "blue")
    

    This basically draws the plot again on top which is not optimal but works well as a quick fix.