Creates a 2D biplot for a pca object, using ggplot2 and ggrepel
to show both sample scores (observations) and variable loadings (arrows).
# S3 method for pca
biplot(
x,
y = NULL,
dims = c(1, 2),
scale_arrows = 2,
alpha_points = 0.6,
point_size = 2,
point_labels = NULL,
var_labels = NULL,
arrow_color = "red",
text_color = "red",
repel_points = TRUE,
repel_vars = FALSE,
...
)A ggplot object.
A pca object returned by pca.
(ignored) Placeholder to match biplot(x, y, ...) signature.
A length-2 integer vector specifying which principal components to plot
on the x and y axes. Defaults to c(1, 2).
A numeric factor to scale the variable loadings (arrows). Default is 2.
Transparency level for the sample points. Default is 0.6.
Size for the sample points. Default is 2.
Optional character vector of labels for the sample points.
If NULL, rownames of the scores matrix are used if available; otherwise numeric indices.
Optional character vector of variable names (columns in the original data).
If NULL, rownames of x\$v are used if available; otherwise "Var1", "Var2", etc.
Color for the loading arrows. Default is "red".
Color for the variable label text. Default is "red".
Logical; if TRUE, repel sample labels using geom_text_repel. Default is TRUE.
Logical; if TRUE, repel variable labels using geom_text_repel. Default is FALSE.
Additional arguments passed on to ggplot2 or ggrepel functions (if needed).
This function constructs a scatterplot of the PCA scores (observations) on two chosen components
and overlays arrows for the loadings (variables). The arrow length and direction indicate how each
variable contributes to those principal components. You can control arrow scaling with scale_arrows.
If your pca object includes an $explained_variance field (e.g., proportion of variance per component),
those values will appear in the axis labels. Otherwise, the axes are labeled simply as "PC1", "PC2", etc.
Note: If you do not have ggrepel installed, you can set repel_points=FALSE and
repel_vars=FALSE, or install ggrepel.
# \donttest{
data(iris)
X <- as.matrix(iris[,1:4])
pca_res <- pca(X, ncomp=2)
# Enhanced biplot with repelled text
biplot(pca_res, repel_points=TRUE, repel_vars=TRUE)
# }
Run the code above in your browser using DataLab