factoextra R Package

repository·master·Indexed 18 days ago

https://github.com/kassambara/factoextra

An R package designed to simplify the extraction and visualization of multivariate data analysis results, including PCA, MCA, MFA, CA, HMFA, and FAMD. It provides a consistent, ggplot2-based interface for interpreting dimensionality reduction and clustering outputs from packages such as FactoMineR, ade4, stats, ca, MASS, and ExPosition. Key features include fviz_* functions for graphical representations, get_* functions for data extraction, and specialized tools for visualizing UMAP, t-SNE, and clustering results.

Tokens
5.7K
Snippets
18
Records
21
Agent score
14%

What's inside factoextra

  1. Overview of factoextra capabilities

    master

    The factoextra package is designed to extract and visualize the results of multivariate data analyses. It provides a unified, human-readable interface for results generated by various R packages (such as FactoMineR, ade4, stats, ca, MASS, and ExPosition).

    Key capabilities include:

    • Extraction: Quickly converting complex analysis outputs into standard, human-readable data formats.
    • Visualization: Producing elegant, ggplot2-based visualizations for dimensionality reduction and clustering.
    • Supported Analyses:
      • Principal Component Analysis (PCA)
      • Correspondence Analysis (CA)
      • Multiple Correspondence Analysis (MCA)
      • Multiple Factor Analysis (MFA)
      • Hierarchical Multiple Factor Analysis (HMFA)
      • Factor Analysis of Mixed Data (FAMD)
  2. Supported advanced multivariate methods

    master

    Beyond classical PCA, CA, and MCA, factoextra provides visualization support for several advanced multivariate methods:

    • FAMD (Factor Analysis of Mixed Data): For datasets containing both qualitative and quantitative variables.
    • MFA (Multiple Factor Analysis): For analyzing datasets organized into groups of variables.
    • HMFA (Hierarchical Multiple Factor Analysis).
    • HCPC (Hierarchical Clustering on Principal Components): Useful for clustering qualitative or mixed datasets.
  3. Visualize Multiple Correspondence Analysis (MCA) results

    master

    For analyzing qualitative variables using FactoMineR::MCA(), use factoextra to visualize variable categories and individuals.

    Key functions:

    • get_mca_var(): Extract results for variable categories.
    • get_mca_ind(): Extract results for individuals.
    • fviz_mca_var(): Graph of variable categories.
    • fviz_mca_ind(): Graph of individuals. Use habillage to color by groups.
    • fviz_mca_biplot(): Biplot of individuals and variables.
    • fviz_contrib(): Visualize contributions (use choice = "var" or choice = "ind").
    library("FactoMineR")
    library("factoextra")
    
    data(poison)
    res.mca <- MCA(poison, quanti.sup = 1:2, quali.sup = 3:4, graph=FALSE)
    
    # Graph of variable categories
    fviz_mca_var(res.mca, repel = TRUE)
    
    # Graph of individuals colored by a group
    grp <- as.factor(poison[, "Vomiting"])
    fviz_mca_ind(res.mca, habillage = grp, addEllipses = TRUE, repel = TRUE)
    
    # Biplot
    fviz_mca_biplot(res.mca, repel = TRUE)
  4. Visualize Principal Component Analysis (PCA) results

    master

    Use factoextra to extract and visualize results from PCA performed with FactoMineR::PCA(). You can visualize eigenvalues (scree plots), variable contributions, variable coordinates, individual coordinates, and biplots.

    Key functions:

    • get_eig(): Extract eigenvalues/variances.
    • fviz_screeplot(): Visualize eigenvalues.
    • get_pca_var(): Extract variable results (coordinates, correlations, cos2, contributions).
    • fviz_pca_var(): Visualize variables. Use col.var = "contrib" to color by contribution.
    • fviz_contrib(): Visualize contributions of variables or individuals to specific axes.
    • get_pca_ind(): Extract individual results.
    • fviz_pca_ind(): Visualize individuals. Use col.ind = "cos2" for quality-based coloring or habillage for group-based coloring.
    • fviz_pca_biplot(): Visualize both individuals and variables together.
    library("factoextra")
    library("FactoMineR")
    
    # 1. Setup data
    data("decathlon2")
    df <- decathlon2[1:23, 1:10]
    
    # 2. Run PCA
    res.pca <- PCA(df, graph = FALSE)
    
    # 3. Visualize eigenvalues
    fviz_screeplot(res.pca, addlabels = TRUE, ylim = c(0, 50))
    
    # 4. Visualize variables (colored by contribution)
    fviz_pca_var(res.pca, col.var="contrib", 
                 gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
                 repel = TRUE)
    
    # 5. Visualize individuals (colored by group)
    fviz_pca_ind(res.pca, 
                 label = "none", 
                 habillage = iris$Species, 
                 palette = c("#00AFBB", "#E7B800", "#FC4E07"),
                 addEllipses = TRUE)
    
    # 6. Biplot
    fviz_pca_biplot(res.pca, repel = TRUE)
  5. Visualize Correspondence Analysis (CA) results

    master

    For analyzing contingency tables using FactoMineR::CA(), use factoextra to extract row/column data and create biplots.

    Key functions:

    • get_ca_row(): Extract results for row variables.
    • get_ca_col(): Extract results for column variables.
    • fviz_ca_biplot(): Biplot of rows and columns.
    • fviz_ca_row(): Graph of row points.
    • fviz_ca_col(): Graph of column points.
    • fviz_contrib(): Visualize row or column contributions to axes (use choice = "row" or choice = "col").
    library("FactoMineR")
    library("factoextra")
    
    data("housetasks")
    res.ca <- CA(housetasks, graph = FALSE)
    
    # Biplot
    fviz_ca_biplot(res.ca, repel = TRUE)
    
    # Row contributions to axis 1
    fviz_contrib(res.ca, choice = "row", axes = 1)
  6. Install and load factoextra

    master

    You can install factoextra from CRAN or the latest development version from GitHub.

    From CRAN:

    install.packages("factoextra")

    From GitHub:

    if(!require(remotes)) install.packages("remotes")
    remotes::install_github("kassambara/factoextra")

    Loading the package:

    library("factoextra")

    Maintenance Baseline Requirements:

    • R >= 4.1.0
    • ggplot2 >= 3.5.2
    • ggpubr >= 0.6.3 (CRAN)
    • FactoMineR >= 2.13
  7. Visualize Clustering results

    master

    Factoextra provides tools to visualize various clustering methods:

    • Partitioning Clustering (e.g., K-means): Use fviz_cluster() to visualize clusters in a 2D space.
    • Hierarchical Clustering: Use fviz_dend() to visualize dendrograms. You can highlight specific branches using the highlight argument.
    • Optimal Clusters: Use fviz_nbclust() with methods like "gap_stat" to determine the optimal number of clusters.
    • Silhouette: Use fviz_silhouette() to visualize silhouette information.
    library(factoextra)
    
    # 1. Partitioning Clustering (K-means)
    km.res <- kmeans(scale(USArrests), 4, nstart = 25)
    fviz_cluster(km.res, data = scale(USArrests))
    
    # 2. Hierarchical Clustering
    res <- hcut(USArrests, k = 4, stand = TRUE)
    fviz_dend(res, rect = TRUE, k_colors = c("#00AFBB", "#2E9FDF", "#E7B800", "#FC4E07"))
    
    # 3. Determine optimal clusters
    fviz_nbclust(scale(USArrests), kmeans, method = "gap_stat")
  8. Visualize UMAP and t-SNE embeddings

    master

    Use fviz_umap() and fviz_tsne() to visualize 2-D embeddings from packages like uwot, Rtsne, umap, or raw coordinate matrices. These functions support coloring by a continuous feature value.

    Note: Because embeddings do not have eigenvalues, axes do not carry percentage explained, and there is no scree or loadings surface.

    # UMAP embedding, coloured by a feature value, with the house theme + palette
    um <- uwot::umap(iris[, 1:4])
    fviz_umap(um, habillage = iris$Species, addEllipses = TRUE,
              palette = factoextra_palette("okabe"), ggtheme = theme_factoextra())
    fviz_umap(um, col.ind = iris$Petal.Length)   # colour by a continuous feature
  9. Visualize tidymodels PCA results

    master

    In version 2.2.0, factoextra introduced an on-ramp for tidymodels. You can convert a PCA fitted within a recipes object (using step_pca()) or a fitted workflow into a factoextra compatible object using as_factoextra_pca(). This allows you to use the fviz_pca_* family of functions directly on tidymodels outputs.

    # tidymodels PCA -> factoextra
    library(recipes)
    rec <- recipe(~ ., data = iris[, 1:4]) |>
      step_normalize(all_numeric_predictors()) |>
      step_pca(all_numeric_predictors(), num_comp = 4)
    prep(rec) |> as_factoextra_pca() |> fviz_pca_biplot(habillage = iris$Species)
  10. Visualize dendrogram branches with highlighting

    master

    The fviz_dend() function allows you to emphasize specific branches leading to certain leaves using the highlight argument.

    # cos2 across several dimensions as a heatmap; large-n scatter; branch highlight
    res.pca <- prcomp(iris[, -5], scale. = TRUE)
    fviz_dend(hclust(dist(scale(USArrests))), k = 4,
              highlight = c("California", "Texas", "New York"))
  11. Determine the optimal number of clusters with fviz_nbclust()

    master

    Use fviz_nbclust() to find the optimal number of clusters for a clustering algorithm. You must provide the data and the clustering function (e.g., kmeans). The method argument specifies the statistical method to use, such as "gap_stat" (Gap Statistic).

    # Optimal number of clusters for k-means
    library("factoextra")
    my_data <- scale(USArrests)
    fviz_nbclust(my_data, kmeans, method = "gap_stat")