PCA in Python: Explained Variance, Scree Plot, Loadings and Biplot

Run PCA in scikit-learn, plot explained variance and a scree plot to choose how many components to keep, read the loadings, and draw a biplot.

To run PCA in Python, standardize your features with StandardScaler, fit PCA() from scikit-learn, and plot pca.explained_variance_ratio_ as a bar chart (a scree plot) with its cumulative sum to see how many components you need. The loadings in pca.components_ say which original features each component is made of, and a biplot puts the data points and those loadings on the same axes. The code targets scikit-learn 1.9.

Quick Example

This builds 600 customers with 9 behavior metrics that are really driven by three hidden traits (engagement, spend and loyalty), then plots the explained variance. It runs without downloads.

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler

rng = np.random.default_rng(14)
n = 600
engagement, value, loyalty = rng.normal(0, 1, (3, n))

df = pd.DataFrame({
    "sessions": 10 + 3 * engagement + rng.normal(0, 1.8, n),
    "pages_per_session": 5 + 1.5 * engagement + rng.normal(0, 1.0, n),
    "minutes_on_site": 22 + 6 * engagement + rng.normal(0, 5, n),
    "email_opens": 8 + 2.5 * engagement + rng.normal(0, 2.5, n),
    "orders": 3 + 1.2 * value + rng.normal(0, 0.9, n),
    "avg_order_value": 55 + 14 * value + rng.normal(0, 9, n),
    "total_spend": 190 + 60 * value + rng.normal(0, 30, n),
    "tenure_months": 24 + 10 * loyalty + rng.normal(0, 6, n),
    "support_tickets": 2 - 0.9 * loyalty + rng.normal(0, 0.9, n),
})

X = StandardScaler().fit_transform(df)
pca = PCA().fit(X)
ratio = pca.explained_variance_ratio_
cum = np.cumsum(ratio)
print("explained variance ratio:", np.round(ratio, 3))
print("cumulative:", np.round(cum, 3))

fig, ax = plt.subplots(figsize=(7.2, 4.4))
comps = np.arange(1, len(ratio) + 1)
ax.bar(comps, ratio, color="#0e7490", label="Per component")
ax.plot(comps, cum, color="#c2410c", marker="o", lw=2, label="Cumulative")
ax.axhline(0.90, color="#94a3b8", ls="--")
ax.set(xlabel="Principal component", ylabel="Explained variance ratio",
       title="PCA explained variance", ylim=(0, 1.05))
ax.set_xticks(comps)
ax.legend(loc="center right")

Bars of explained variance for 9 principal components, 31%, 27% and 17% for the first three and under 7% each after, with a cumulative line crossing the dashed 90% mark at component 6

The first three components explain 31%, 27% and 17% of the variance (75.6% together). From component 4 on, each adds under 7%. That sharp drop after component 3 is the "elbow" of the scree plot, and it matches how the data was made: nine columns, three hidden traits. The cumulative line crosses 90% at component 6.

How Many Components Should You Keep?

There is no single right answer. Three common rules, and what each says here:

Rule How Result on this data
Scree elbow Keep components before the curve flattens 3
Kaiser rule Keep components with pca.explained_variance_ > 1 (on standardized data) 3
Variance threshold Smallest number that reaches 80% to 95% 6 for 90%

The threshold rule has a shortcut: PCA(n_components=0.90) picks the number of components that reaches 90% automatically, and pca.n_components_ tells you how many it kept (6 here). The elbow and Kaiser rules aim at the "signal" components, and the threshold rule aims at preserving information. If you are compressing features for a model, use the threshold and tune it by cross-validation. If you are looking for structure to interpret, the elbow is more useful.

Read the Loadings: What Is Each Component Made Of?

pca.components_ has one row per component and one column per original feature. Each value is a loading: the weight of that feature in the component.

loadings = pd.DataFrame(pca.components_[:3].T, index=df.columns,
                        columns=["PC1", "PC2", "PC3"])
print(loadings.round(2))

Three horizontal bar charts of loadings: PC1 loads on sessions, pages per session, minutes on site and email opens; PC2 on orders, average order value and total spend; PC3 positively on tenure and negatively on support tickets

  • PC1 (31%) loads about 0.45 to 0.53 on sessions, pages_per_session, minutes_on_site and email_opens, and about 0 on everything else. It is an engagement axis.
  • PC2 (27%) loads 0.54 to 0.57 on orders, avg_order_value and total_spend. It is a spend axis.
  • PC3 (17%) loads +0.69 on tenure_months and -0.68 on support_tickets. It separates long-tenured, low-ticket customers from newer ones with more tickets.

PCA recovered the three traits that were put into the data, because the traits were independent. Real data rarely separates this cleanly, and loadings are often a blend. Signs are arbitrary: PCA can flip a whole component, so -PC1 is as valid as PC1. Interpret relative signs within a component, not the sign of the component.

Draw a Biplot

A biplot shows each row's scores on the first two components as points, with the original features drawn as arrows from the origin. The arrow for a feature is its PC1 and PC2 loading, scaled up to be visible.

scores = pca.transform(X)
fig, ax = plt.subplots(figsize=(7.6, 6.2))
sc = ax.scatter(scores[:, 0], scores[:, 1], c=df["total_spend"], cmap="viridis",
                s=16, alpha=0.7)
fig.colorbar(sc, ax=ax, label="total_spend", shrink=0.85)

scale = 4.2
for i, name in enumerate(df.columns):
    x, y = pca.components_[0, i] * scale, pca.components_[1, i] * scale
    ax.annotate("", xy=(x, y), xytext=(0, 0),
                arrowprops=dict(arrowstyle="->", color="#be123c", lw=1.4))
    ax.text(x * 1.1, y * 1.1, name, fontsize=8, color="#9f1239", ha="center")
ax.set(xlabel=f"PC1 ({ratio[0]:.0%})", ylabel=f"PC2 ({ratio[1]:.0%})",
       title="PCA biplot: customers and feature loadings")

Scatter of customers on PC1 and PC2 colored by total spend, with arrows for engagement features pointing right along PC1 and spend features pointing up along PC2; spend color increases toward the top

Reading it:

  • Arrow direction shows which component a feature drives. The four engagement metrics point right (PC1), and the three spend metrics point up (PC2).
  • Arrows that point the same way are positively correlated features. orders, avg_order_value and total_spend are nearly on top of each other.
  • Arrows at right angles are roughly uncorrelated. Engagement and spend are independent here.
  • Point color confirms the axis. Customers at the top of the plot have the highest total_spend, which is what the arrows predicted.

The version drawn for this post moves the labels off the arrows with annotate leader lines because the arrows overlap, which is common when several features point the same way. The simple ax.text loop above is the minimal version. Only 58% of the variance (PC1 + PC2) appears in this plot, and the loyalty trait (PC3) is not visible at all, so use a PC1 vs PC3 biplot when you need it.

Why You Must Scale Before PCA

PCA finds directions of maximum variance, so a column in large units dominates. Running PCA() on the raw df gives:

raw = PCA().fit(df)
print(np.round(raw.explained_variance_ratio_[:3], 3))
print(dict(zip(df.columns, np.round(raw.components_[0], 2))))

The first component then explains 93.3% of the variance and is simply total_spend (loading 0.98), whose variance is 4,358 against 1.7 for support_tickets. The other eight columns barely contribute. After StandardScaler, every column has variance 1, and the structure shows up. Scale unless all of your features share the same units and the differences in variance are meaningful.

PCA vs Other Dimensionality Reduction

Need Use
Compress correlated numeric features, feed a model PCA with n_components=0.9
Understand which features move together PCA loadings and a biplot
Visualize clusters in 2D when structure is nonlinear t-SNE or UMAP (they are for plotting, not for downstream features)
Sparse text matrices TruncatedSVD (PCA centers the data, which makes sparse input dense)

Practical Tips

  • Fit the scaler and PCA on training data only, then transform the test set. Put both in a Pipeline so cross-validation doesn't leak.
  • explained_variance_ratio_ sums to 1 only when you keep all components. With n_components=2, it holds the share of the original variance those two keep.
  • Components are linear combinations, so PCA can't capture curved structure. If the biplot looks like a horseshoe, try a nonlinear method.
  • Categorical columns need encoding first, and one-hot columns usually don't suit PCA. Consider MCA or a different method.
  • To see whether clusters exist in the reduced space, see K-Means Elbow Method and Silhouette Plot in Python.

Similar Topics