How to Make a PCA Biplot in StatFas, SPSS, R, Python and MATLAB
This tutorial makes the same PCA biplot five ways, so you can pick the tool you already use. All examples use a table with one row per sample, a group column and eight numeric biomarkers (glucose, insulin, hba1c, ldl, hdl, tg, bmi, crp).
What you will make
A publication-ready PCA biplot with the compulsory checks and statistics that go with it, produced in five ways. The StatFas generator needs no coding and no account to run; the code versions are for readers who want a scripted workflow. For the theory behind the plot and how to read it, see the full guide.
Example data
| Column | Contents |
|---|---|
group | Control, Prediabetes or T2DM (optional grouping column) |
glucose … crp | Eight numeric biomarkers, one column each |
Save your table as data.csv with a header row. The StatFas generator has a Load Example Data button with simulated data, so you can follow along without your own file. The example data are invented for illustration and are not real findings.
Method 1: StatFas (free, no coding)
- Open the PCA Biplot Generator and click Load Example Data (60 invented participants in three groups) or paste/upload your own file.
- Choose the variables, set Colour samples by group, and keep Analysed matrix on Correlation (standardised). Set the components on the x- and y-axes (default PC1 and PC2).
- Click Run analysis. Read the KMO and Bartlett table, the eigenvalue table with parallel analysis, the loadings table, and the biplot and scree figures.
- Open Appearance Settings and the figure style panel to change colors (including a colour-blind safe palette), font, font size, line width and marker size.
- Log in (free) and download each figure (PNG or SVG), each table (CSV) or the full Word report with APA7 interpretations.
Method 2: SPSS
SPSS has no biplot command, but you can run the PCA with KMO and Bartlett, save the component scores and plot them. In the menus: Analyze > Dimension Reduction > Factor, choose Extraction: Principal components, tick KMO and Bartlett’s test and Scree plot, and Scores > Save as variables. Equivalent syntax:
FACTOR
/VARIABLES glucose insulin hba1c ldl hdl tg bmi crp
/PRINT INITIAL KMO EXTRACTION
/PLOT EIGEN
/CRITERIA MINEIGEN(1) ITERATE(25)
/EXTRACTION PC
/ROTATION NOROTATE
/SAVE REG(ALL)
/METHOD=CORRELATION.
GRAPH /SCATTERPLOT(BIVAR)=FAC1_1 WITH FAC2_1 BY group.SPSS uses the eigenvalue > 1 rule by default. For parallel analysis use O’Connor’s syntax or the R plug-in. Loading arrows are not drawn; use R, Python or StatFas for a true biplot.
Method 3: R
library(readr); library(psych); library(factoextra)
df <- read_csv("pca.csv"); X <- df[, -1]
KMO(cor(X)) # sampling adequacy
cortest.bartlett(cor(X), n = nrow(X)) # Bartlett's test
fa.parallel(X, fa = "pc", n.iter = 500) # Horn's parallel analysis
pca <- prcomp(X, scale. = TRUE)
summary(pca) # eigenvalues and % variance
fviz_pca_biplot(pca, habillage = factor(df$group), addEllipses = TRUE,
label = "var", repel = TRUE)
ggplot2::ggsave("pca_biplot.png", width = 6, height = 5, dpi = 300)Packages: install.packages(c("readr","psych","factoextra")). prcomp(scale. = TRUE) runs PCA on the correlation matrix.
Method 4: Python
import numpy as np, pandas as pd, matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from scipy.stats import chi2
df = pd.read_csv("pca.csv") # columns: group + 8 numeric biomarkers
X = df.drop(columns="group")
Z = StandardScaler().fit_transform(X) # correlation-matrix PCA
# Suitability: Bartlett's test of sphericity and KMO
R = np.corrcoef(Z, rowvar=False); n, p = Z.shape
chi_sq = -(n - 1 - (2 * p + 5) / 6) * np.log(np.linalg.det(R))
df_b = p * (p - 1) / 2
print(f"Bartlett chi2({df_b:.0f}) = {chi_sq:.1f}, p = {chi2.sf(chi_sq, df_b):.4g}")
Rinv = np.linalg.inv(R); S = -Rinv / np.sqrt(np.outer(np.diag(Rinv), np.diag(Rinv)))
off = ~np.eye(p, dtype=bool)
print("KMO =", round((R[off]**2).sum() / ((R[off]**2).sum() + (S[off]**2).sum()), 3))
# PCA and Horn's parallel analysis (95th percentile of random eigenvalues)
pca = PCA().fit(Z); eig = pca.explained_variance_
rng = np.random.default_rng(1)
rand = np.array([np.linalg.eigvalsh(np.corrcoef(rng.standard_normal((n, p)), rowvar=False))[::-1] for _ in range(500)])
keep = int((eig > np.percentile(rand, 95, axis=0)).sum())
print("Components to keep:", keep, "| % variance:", np.round(pca.explained_variance_ratio_ * 100, 1))
# Biplot of PC1 vs PC2
scores = pca.transform(Z)[:, :2]; load = pca.components_[:2].T * np.sqrt(eig[:2])
fig, ax = plt.subplots(figsize=(6, 5))
for g in df["group"].unique():
m = (df["group"] == g).values; ax.scatter(scores[m, 0], scores[m, 1], label=g, s=25)
k = np.abs(scores).max() / np.abs(load).max() * 0.9
for (x, y), name in zip(load * k, X.columns):
ax.arrow(0, 0, x, y, color="k", width=0.005, head_width=0.12); ax.text(x * 1.08, y * 1.08, name, ha="center")
ax.set_xlabel(f"PC1 ({pca.explained_variance_ratio_[0]*100:.1f}%)"); ax.set_ylabel(f"PC2 ({pca.explained_variance_ratio_[1]*100:.1f}%)")
ax.legend(); fig.tight_layout(); fig.savefig("pca_biplot.png", dpi=300)Requires numpy, pandas, scikit-learn, scipy and matplotlib. The script computes Bartlett and KMO by hand because scikit-learn does not include them; the factor_analyzer package also provides both.
Method 5: MATLAB, OriginPro, Excel and others
MATLAB
T = readtable("pca.csv"); X = zscore(T{:, 2:end}); vars = T.Properties.VariableNames(2:end);
[coeff, score, latent, ~, explained] = pca(X);
biplot(coeff(:, 1:2), "Scores", score(:, 1:2), "VarLabels", vars);OriginPro / Excel
OriginPro: Statistics > Multivariate Analysis > Principal Component Analysis outputs a biplot (menu names vary slightly between versions). Excel has no built-in PCA; use an add-in or export the table to StatFas.
Which method should you choose?
| Tool | Cost and skill | Plot | Statistical checks | Report-ready output |
|---|---|---|---|---|
| StatFas | Free, in the browser | Yes (with groups, ellipses) | Yes | Yes, to Word |
| SPSS | Licence needed | No (scores scatter only) | KMO/Bartlett yes; parallel needs syntax | Tables only |
| R | Free, coding | Yes (factoextra) | Yes (psych) | Manual |
| Python | Free, coding | Yes (custom) | Manual or factor_analyzer | Manual |
Choose StatFas for speed and APA7-ready output, SPSS if your department already licenses it and you only need the statistics, and R or Python when the analysis must be scripted and reproduced in a pipeline.
How to report the result in APA7
Report the KMO value and Bartlett’s χ² (with degrees of freedom and p), the retention rule, the number of components retained with eigenvalues and percentage of variance, and salient loadings. Number the biplot as a figure and note the scaling. StatFas writes this paragraph and the loadings table for you.
See the guide for an example paragraph.
Troubleshooting
- The biplot arrows are all tiny or huge. Arrow scaling differs between programs. Scale loadings to the range of the scores, as in the Python example, or use the generator, which does this automatically.
- Signs are flipped compared with another program. Component signs are arbitrary. Flip the sign of a component if it helps interpretation; the information is the same.
- Error: system is computationally singular. Two variables are perfectly or almost perfectly correlated, or there are more variables than samples. Remove redundant variables.
- Missing values. PCA needs complete rows. Remove or impute missing values before running it.
Frequently asked questions
Which software is best for a PCA biplot?
For a quick, publication-ready biplot with checks and APA7 text, a browser tool such as the StatFas generator is fastest. R and Python give full scripting control.
Can SPSS make a biplot?
Not directly. Save the component scores and plot them, or use another program for loading arrows.
Related tools, guides and tutorials
- Guide: PCA Biplot Explained: How to Make, Read and Report It
- PCA calculator
- PCA tutorial
- Principal component analysis explained
- Exploratory factor analysis
- EFA tutorial
- Heatmap maker
- Hypothesis and analysis suggester
- Parallel Coordinates Plot Generator
- 3D Scatter Plot Generator
- Ternary Plot Generator
- All tutorials
- All blog posts
References
- American Psychological Association. (2020). Publication manual of the American Psychological Association (7th ed.).
- Bartlett, M. S. (1954). A note on the multiplying factors for various χ² approximations. Journal of the Royal Statistical Society B, 16(2), 296–298.
- Gabriel, K. R. (1971). The biplot graphic display of matrices with application to principal component analysis. Biometrika, 58(3), 453–467.
- Horn, J. L. (1965). A rationale and test for the number of factors in factor analysis. Psychometrika, 30(2), 179–185.
- Jolliffe, I. T., & Cadima, J. (2016). Principal component analysis: A review and recent developments. Philosophical Transactions of the Royal Society A, 374(2065), 20150202.