% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/fviz_nbclust.R
\name{fviz_nbclust}
\alias{fviz_nbclust}
\alias{fviz_gap_stat}
\title{Determining and Visualizing the Optimal Number of Clusters}
\usage{
fviz_nbclust(
  x,
  FUNcluster = NULL,
  method = c("silhouette", "wss", "gap_stat"),
  diss = NULL,
  k.max = 10,
  nboot = 100,
  verbose = interactive(),
  barfill = "steelblue",
  barcolor = "steelblue",
  linecolor = "steelblue",
  print.summary = TRUE,
  ...
)

fviz_gap_stat(
  gap_stat,
  linecolor = "steelblue",
  maxSE = list(method = "firstSEmax", SE.factor = 1)
)
}
\arguments{
\item{x}{numeric matrix or data frame. In the function fviz_nbclust(), x can
be the results of the function NbClust(). For \code{method = "silhouette"}
or \code{"wss"}, x may also be a precomputed dissimilarity (an object of
class \code{"dist"}); it is then passed directly to \code{FUNcluster},
which must be a dissimilarity-capable method (e.g. \code{cluster::pam} or
\code{factoextra::hcut}). \code{method = "gap_stat"} still needs the raw data.}

\item{FUNcluster}{a partitioning function which accepts as first argument a
(data) matrix like \code{x}, second argument, say \code{k >= 2}, the
number of clusters desired, and returns a list with a component named
\code{cluster} which contains the grouping of observations. Allowed values
include: \code{kmeans}, \code{cluster::pam}, \code{cluster::clara},
\code{cluster::fanny}, \code{hcut}, etc. In \code{method = "wss"} mode,
\code{fviz_nbclust()} computes the \code{k = 1} baseline internally instead
of calling \code{FUNcluster(x, 1, ...)}. This argument is not required
when \code{x} is an output of the function \code{NbClust::NbClust()}.}

\item{method}{the method to be used for estimating the optimal number of 
clusters. Possible values are "silhouette" (for average silhouette width), 
"wss" (for total within sum of square) and "gap_stat" (for gap statistics).}

\item{diss}{dist object as produced by dist(), i.e.: diss = dist(x, method = 
"euclidean"). Used to compute the average silhouette width of clusters, the
within sum of square and hierarchical clustering. If NULL, dist(x) is 
computed with the default method = "euclidean"}

\item{k.max}{the maximum number of clusters to consider, must be at least two.}

\item{nboot}{integer, number of Monte Carlo ("bootstrap") samples. Used only for determining the number of clusters 
using gap statistic.}

\item{verbose}{logical value. If TRUE, the result of progress is printed.}

\item{barfill, barcolor}{fill color and outline color for bars}

\item{linecolor}{color for lines}

\item{print.summary}{logical value. If true, the optimal number of clusters 
are printed in fviz_nbclust().}

\item{...}{optionally further arguments:
arguments for FUNcluster() in "wss"/"silhouette" modes; arguments for
\code{\link[cluster]{clusGap}}() in "gap_stat" mode. A \code{maxSE} list
can also be supplied in "gap_stat" mode and is forwarded to
\code{fviz_gap_stat()}.}

\item{gap_stat}{an object of class "clusGap" returned by the function
clusGap() [in cluster package]}

\item{maxSE}{a list containing the parameters (method and SE.factor) for
determining the location of the maximum of the gap statistic (Read the
documentation ?cluster::maxSE). Allowed values for maxSE$method include:
\itemize{ \item "globalmax": simply corresponds to the global maximum,
i.e., is which.max(gap) \item "firstmax": gives the location of the first
local maximum \item "Tibs2001SEmax": uses the criterion, Tibshirani et al
(2001) proposed: "the smallest k such that gap(k) >= gap(k+1) - s(k+1)".
It's also possible to use "the smallest k such that gap(k) >= gap(k+1) -
SE.factor*s(k+1)" where SE.factor is a numeric value which can be 1
(default), 2, 3, etc. \item "firstSEmax": location of the first f() value
which is not larger than the first local maximum minus SE.factor * SE.f,
i.e, within an "f S.E." range of that maximum. \item
see ?cluster::maxSE for more options }}
}
\value{
\itemize{ \item fviz_nbclust, fviz_gap_stat: return a ggplot2 }
}
\description{
Partitioning methods, such as k-means clustering require the 
  users to specify the number of clusters to be generated. \itemize{
  \item fviz_nbclust(): Determines and visualizes the optimal number of
  clusters using different methods: \strong{within cluster sums of squares},
  \strong{average silhouette} and \strong{gap statistics}. Silhouette values
  are evaluated only for \code{k = 2, \ldots, k.max} because average
  silhouette width is undefined for a one-cluster partition. The dashed
  guide line marks the best displayed silhouette width among those
  \code{k >= 2} candidates.
  \item fviz_gap_stat(): Visualizes the gap statistic generated by the
  function \code{\link[cluster]{clusGap}}() [in cluster package]. The optimal
  number of clusters is specified using the "firstmax" method
  (?cluster::clustGap). }

  For \code{method = "wss"}, \code{factoextra} computes the \code{k = 1}
  baseline internally so helper functions such as \code{hcut()} and
  \code{hkmeans()} can keep rejecting direct \code{k = 1} inputs.

  Read more:
  \href{https://www.datanovia.com/en/lessons/determining-the-optimal-number-of-clusters-3-must-know-methods/}{Determining
   the optimal number of clusters}
}
\section{Method selection for gap statistic}{

  The default method "firstSEmax" (developed by Martin Maechler, 2012) is
  recommended as a robust alternative to "Tibs2001SEmax". The original
  Tibshirani method can be overly conservative and often returns k=1 when
  standard deviations are large relative to gap differences. The "firstSEmax"
  method finds the smallest k within one standard error of the first local
  maximum, providing more stable results in practice.
}

\examples{
set.seed(123)

# Data preparation
# +++++++++++++++
data("iris")
head(iris)
# Remove species column (5) and scale the data
iris.scaled <- scale(iris[, -5])


# Optimal number of clusters in the data
# ++++++++++++++++++++++++++++++++++++++
# Examples are provided only for kmeans, but
# you can also use cluster::pam (for pam) or
#  hcut (for hierarchical clustering)
 
### Elbow method (look at the knee)
# Elbow method for kmeans
fviz_nbclust(iris.scaled, kmeans, method = "wss") +
geom_vline(xintercept = 3, linetype = 2)

# WSS with hierarchical clustering keeps the internal k = 1 baseline
fviz_nbclust(iris.scaled, hcut, method = "wss", hc_method = "complete")

# Average silhouette for kmeans
fviz_nbclust(iris.scaled, kmeans, method = "silhouette")

### Gap statistic
library(cluster)
set.seed(123)
# Compute gap statistic for kmeans
# we used B = 10 for demo. Recommended value is ~500
gap_stat <- clusGap(iris.scaled, FUN = kmeans, nstart = 25,
 K.max = 10, B = 10)
 print(gap_stat, method = "firstmax")
fviz_gap_stat(gap_stat)
 
# Gap statistic for hierarchical clustering
gap_stat <- clusGap(iris.scaled, FUN = hcut, K.max = 10, B = 10)
fviz_gap_stat(gap_stat)

 
}
\seealso{
\code{\link{fviz_cluster}}, \code{\link{eclust}}
}
\author{
Alboukadel Kassambara \email{alboukadel.kassambara@gmail.com}
}
