Principal Component Analysis
An expression experiment measures thousands of genes in a few dozen samples, and no plot has thousands of axes. Principal component analysis, or PCA, replaces the genes with a few new axes, each a weighted sum of genes, ordered by how much of the variation between samples they carry. A plot of the first two shows which samples resemble each other. This page runs PCA on a small expression matrix in R and Python and reads the three results: the variance explained, the sample scores, and the gene loadings.
When to use PCA
Section titled “When to use PCA”Use PCA to explore a dataset and to check its quality before differential expression or clustering. The method never sees the group labels. It finds the directions of largest variation, and those directions can come from the biology you study, from a processing batch, or from one unusual sample.
Get the data
Section titled “Get the data”Download expression_matrix.csv into your working directory. The invented table has 60 rows, one per sample, and 52 columns: a sample label, a group label, and 50 genes named gene_00 to gene_49. Every value was drawn from a normal distribution with a standard deviation of 1, so all genes are on one scale, as log expression values are.
The simulation has a known answer. Groups A and B hold 30 samples each, and group B is shifted up by 2.5 units in the first ten genes, gene_00 to gene_09. The other 40 genes are noise.
library(ggplot2)
expression <- read.csv("expression_matrix.csv")genes <- grep("^gene_", names(expression), value = TRUE)gene_matrix <- as.matrix(expression[, genes])dir.create("outputs", showWarnings = FALSE)cat(sprintf("%d samples, %d genes\n", nrow(gene_matrix), ncol(gene_matrix)))for (group_name in c("A", "B")) { cat(sprintf("Group %s: %d samples\n", group_name, sum(expression$group == group_name)))}60 samples, 50 genesGroup A: 30 samplesGroup B: 30 samplesfrom pathlib import Path
import matplotlib.pyplot as pltimport pandas as pdfrom sklearn.decomposition import PCAfrom sklearn.preprocessing import StandardScaler
expression = pd.read_csv("expression_matrix.csv")genes = [name for name in expression.columns if name.startswith("gene_")]gene_matrix = expression[genes]output = Path("outputs")output.mkdir(exist_ok=True)print(f"{gene_matrix.shape[0]} samples, {gene_matrix.shape[1]} genes")for group_name in ("A", "B"): group_size = (expression["group"] == group_name).sum() print(f"Group {group_name}: {group_size} samples")60 samples, 50 genesGroup A: 30 samplesGroup B: 30 samplesRun the PCA
Section titled “Run the PCA”prcomp() in R and PCA in scikit-learn both center each gene and leave its scale unchanged by default. That default suits this matrix, because every gene is on the same scale. The section on scaling below returns to the choice.
Each component has a variance, and its share of the total variance tells you how much of the variation between samples that axis carries.
pca <- prcomp(gene_matrix, center = TRUE, scale. = FALSE)variance_share <- pca$sdev^2 / sum(pca$sdev^2)for (i in 1:5) { cat(sprintf("PC%d: %.1f%%\n", i, 100 * variance_share[i]))}PC1: 27.3%PC2: 4.9%PC3: 4.6%PC4: 4.4%PC5: 4.0%pca = PCA()pca.fit(gene_matrix)variance_share = pca.explained_variance_ratio_for i in range(5): print(f"PC{i + 1}: {100 * variance_share[i]:.1f}%")PC1: 27.3%PC2: 4.9%PC3: 4.6%PC4: 4.4%PC5: 4.0%The two languages agree. PC1 carries 27.3% of the variance, and no later component carries more than 4.9%. One axis dominates, as the simulation intends, with one group difference and noise everywhere else.
A share of 27.3% can look modest for the only signal in the data. The remaining variance is spread thinly over the other 49 components, so judge PC1 against PC2 and the components after it.
The scree plot
Section titled “The scree plot”A scree plot draws the variance share of each component in order. Look for the point where the bars stop falling steeply.
scree <- data.frame(component = factor(1:10), share = 100 * variance_share[1:10])scree_plot <- ggplot(scree, aes(x = component, y = share)) + geom_col(fill = "#1f4e5f", width = 0.7) + labs(x = "Principal component", y = "Variance explained (%)", title = "Scree plot") + theme_minimal(base_size = 13)ggsave("outputs/pca-scree-r.png", scree_plot, width = 5, height = 4, dpi = 150)
figure, axis = plt.subplots(figsize=(5, 4))axis.bar(range(1, 11), 100 * variance_share[:10], color="#1f2a44", width=0.7)axis.set_xticks(range(1, 11))axis.set(xlabel="Principal component", ylabel="Variance explained (%)", title="Scree plot")figure.tight_layout()figure.savefig(output / "pca-scree-python.png", dpi=150)plt.close(figure)
The first bar stands alone, and bars 2 to 10 fall slowly from 4.9%. The break after PC1 is the elbow. In this matrix one component carries the structure and the rest describe noise. Expect a less tidy picture from real data: when the bars fall gradually, the plot offers no single cutoff, and a component past the bend can still carry a small real difference.
The sample scores
Section titled “The sample scores”The scores are the coordinates of each sample on the new axes. Plot PC1 against PC2 and color the points by group. The code also prints the range of PC1 within each group.
scores <- data.frame(PC1 = pca$x[, 1], PC2 = pca$x[, 2], group = expression$group)for (group_name in c("A", "B")) { pc1 <- scores$PC1[scores$group == group_name] cat(sprintf("Group %s: PC1 from %.2f to %.2f\n", group_name, min(pc1), max(pc1)))}score_plot <- ggplot(scores, aes(x = PC1, y = PC2, color = group)) + geom_point(size = 2.5, alpha = 0.8) + scale_color_manual(values = c(A = "#69b3a2", B = "#e07a5f")) + labs(x = sprintf("PC1 (%.1f%%)", 100 * variance_share[1]), y = sprintf("PC2 (%.1f%%)", 100 * variance_share[2]), title = "PCA scores") + theme_minimal(base_size = 13)ggsave("outputs/pca-scores-r.png", score_plot, width = 5, height = 4, dpi = 150)Group A: PC1 from -5.54 to -2.28Group B: PC1 from 1.83 to 7.62
coordinates = pca.transform(gene_matrix)scores = pd.DataFrame({"PC1": coordinates[:, 0], "PC2": coordinates[:, 1], "group": expression["group"]})colors = {"A": "#69b3a2", "B": "#e07a5f"}figure, axis = plt.subplots(figsize=(5, 4))for group_name in ("A", "B"): members = scores[scores["group"] == group_name] print(f"Group {group_name}: PC1 from {members['PC1'].min():.2f} " f"to {members['PC1'].max():.2f}") axis.scatter(members["PC1"], members["PC2"], color=colors[group_name], alpha=0.8, s=40, label=group_name)axis.set(xlabel=f"PC1 ({100 * variance_share[0]:.1f}%)", ylabel=f"PC2 ({100 * variance_share[1]:.1f}%)", title="PCA scores")axis.legend(title="group", loc="lower center")figure.tight_layout()figure.savefig(output / "pca-scores-python.png", dpi=150)plt.close(figure)Group A: PC1 from -5.54 to -2.28Group B: PC1 from 1.83 to 7.62
Group A spans -5.54 to -2.28 on PC1 and group B spans 1.83 to 7.62. The two ranges do not overlap, and a gap of about 4 units separates them. PC2 does not separate the groups, since both clouds cover the same vertical range. PCA found the group difference without the labels because the simulated shift is the largest source of variation in the matrix.
In an experiment, color the same plot by processing date, batch, and every other recorded covariate. If the split on PC1 followed the sequencing batch and not the biological group, PC1 would describe a batch effect, and every comparison between the groups would inherit it.
Which genes drive PC1
Section titled “Which genes drive PC1”A component is a weighted sum of the genes, and the weights are the loadings. A gene with a loading near zero contributes almost nothing to the component. The helper below ranks the genes by the absolute value of their PC1 loading, and the code then compares the top ten with the ten genes that the simulation shifted.
#' Rank the variables of one principal component by absolute loading.#'#' @param rotation The rotation matrix of a prcomp object.#' @param component The index of the principal component.#' @param count The number of variables to return.#' @return A named numeric vector of loadings, largest absolute value first.TopLoadings <- function(rotation, component = 1, count = 10) { loadings <- rotation[, component] ranked <- order(abs(loadings), decreasing = TRUE) loadings[ranked[seq_len(count)]]}
shifted_genes <- sprintf("gene_%02d", 0:9)noise_genes <- setdiff(genes, shifted_genes)top_ten <- TopLoadings(pca$rotation)for (gene in names(top_ten)) { cat(sprintf("%s %6.3f\n", gene, top_ten[gene]))}cat(sprintf("Shifted genes in the top ten: %d\n", sum(names(top_ten) %in% shifted_genes)))cat(sprintf("Largest absolute loading of a noise gene: %.3f\n", max(abs(pca$rotation[noise_genes, 1]))))gene_04 0.356gene_07 0.339gene_01 0.328gene_08 0.326gene_00 0.310gene_03 0.298gene_09 0.289gene_05 0.284gene_06 0.272gene_02 0.268Shifted genes in the top ten: 10Largest absolute loading of a noise gene: 0.118def top_loadings(model, names, component=0, count=10): """Rank the variables of one principal component by absolute loading.
Args: model: A fitted scikit-learn PCA object. names: The variable names, in column order. component: The zero-based index of the principal component. count: The number of variables to return.
Returns: A pandas Series of loadings, largest absolute value first. """ loadings = pd.Series(model.components_[component], index=names) ranked = loadings.abs().sort_values(ascending=False).index[:count] return loadings[ranked]
shifted_genes = [f"gene_{i:02d}" for i in range(10)]noise_genes = [name for name in genes if name not in shifted_genes]top_ten = top_loadings(pca, genes)for gene, loading in top_ten.items(): print(f"{gene} {loading:6.3f}")print("Shifted genes in the top ten: " f"{top_ten.index.isin(shifted_genes).sum()}")all_loadings = pd.Series(pca.components_[0], index=genes)print("Largest absolute loading of a noise gene: " f"{all_loadings[noise_genes].abs().max():.3f}")gene_04 0.356gene_07 0.339gene_01 0.328gene_08 0.326gene_00 0.310gene_03 0.298gene_09 0.289gene_05 0.284gene_06 0.272gene_02 0.268Shifted genes in the top ten: 10Largest absolute loading of a noise gene: 0.118All ten of the largest loadings belong to the ten shifted genes, with values from 0.268 to 0.356. The largest absolute loading among the 40 noise genes is 0.118. PC1 is close to an average of the ten shifted genes: an exact average of ten genes would give each one a loading of 0.316, the square root of one tenth.
The loadings are positive in both languages here, so a high PC1 score means high expression of these ten genes, and group B sits on the right of the score plot. Do not rely on that direction. The sign of a component is arbitrary, and the prcomp() help page warns that it can differ between programs and between builds of R. A flipped sign reverses every loading and every score of the component together, so compare absolute loadings between programs and read the direction from the loadings and the scores of one run.
A large loading describes the component and carries no p-value. For a claim about one gene, fit a model for that gene.
When to scale the variables
Section titled “When to scale the variables”Scaling divides each centered variable by its standard deviation, so every variable enters the PCA with a variance of 1. Whether that helps depends on what the variances mean.
Scale when the variables have different units or different ranges. Without scaling, the variable whose units give it the largest variance takes over PC1, whatever it measures.
Leave the scale alone when all variables share one scale and a larger variance means more signal, as with log expression values. Scaling then gives a noisy gene with little variation the same weight as a gene that separates the groups. In this matrix the ten shifted genes have the larger standard deviations, and the code below shows what scaling does to them.
gene_sd <- apply(gene_matrix, 2, sd)cat(sprintf("SD of the shifted genes: %.2f to %.2f\n", min(gene_sd[shifted_genes]), max(gene_sd[shifted_genes])))cat(sprintf("SD of the noise genes: %.2f to %.2f\n", min(gene_sd[noise_genes]), max(gene_sd[noise_genes])))scaled_pca <- prcomp(gene_matrix, center = TRUE, scale. = TRUE)scaled_share <- scaled_pca$sdev^2 / sum(scaled_pca$sdev^2)scaled_top <- TopLoadings(scaled_pca$rotation)cat(sprintf("Centered only: PC1 %.1f%%, PC2 %.1f%%\n", 100 * variance_share[1], 100 * variance_share[2]))cat(sprintf("Centered and scaled: PC1 %.1f%%, PC2 %.1f%%\n", 100 * scaled_share[1], 100 * scaled_share[2]))cat(sprintf("Shifted genes in the scaled top ten: %d\n", sum(names(scaled_top) %in% shifted_genes)))SD of the shifted genes: 1.52 to 1.71SD of the noise genes: 0.86 to 1.13Centered only: PC1 27.3%, PC2 4.9%Centered and scaled: PC1 14.9%, PC2 6.0%Shifted genes in the scaled top ten: 10gene_sd = gene_matrix.std()print(f"SD of the shifted genes: {gene_sd[shifted_genes].min():.2f} " f"to {gene_sd[shifted_genes].max():.2f}")print(f"SD of the noise genes: {gene_sd[noise_genes].min():.2f} " f"to {gene_sd[noise_genes].max():.2f}")scaled_matrix = StandardScaler().fit_transform(gene_matrix)scaled_pca = PCA()scaled_pca.fit(scaled_matrix)scaled_share = scaled_pca.explained_variance_ratio_scaled_top = top_loadings(scaled_pca, genes)print(f"Centered only: PC1 {100 * variance_share[0]:.1f}%, " f"PC2 {100 * variance_share[1]:.1f}%")print(f"Centered and scaled: PC1 {100 * scaled_share[0]:.1f}%, " f"PC2 {100 * scaled_share[1]:.1f}%")print("Shifted genes in the scaled top ten: " f"{scaled_top.index.isin(shifted_genes).sum()}")SD of the shifted genes: 1.52 to 1.71SD of the noise genes: 0.86 to 1.13Centered only: PC1 27.3%, PC2 4.9%Centered and scaled: PC1 14.9%, PC2 6.0%Shifted genes in the scaled top ten: 10The shifted genes have standard deviations of 1.52 to 1.71, and the noise genes have 0.86 to 1.13. The extra spread of the shifted genes is the group difference. Scaling divides it away, and the share of PC1 falls from 27.3% to 14.9% while the share of PC2 rises from 4.9% to 6.0%.
The ten shifted genes still lead PC1 after scaling, because they still rise and fall together and scaling does not change a correlation. The margin of PC1 over PC2 is smaller, though. Scaling discarded the one piece of information that set the informative genes apart before the PCA started, their larger variance.
Now break the common scale on purpose. Multiply gene_49, a noise gene, by 100, as if one column held percentages and the others held fractions, and run both versions again.
mixed_units <- gene_matrixmixed_units[, "gene_49"] <- 100 * mixed_units[, "gene_49"]mixed_pca <- prcomp(mixed_units, center = TRUE, scale. = FALSE)mixed_share <- mixed_pca$sdev^2 / sum(mixed_pca$sdev^2)mixed_top <- TopLoadings(mixed_pca$rotation, count = 1)cat(sprintf("Centered only: PC1 share %.1f%%, top gene %s, loading %.3f\n", 100 * mixed_share[1], names(mixed_top), abs(mixed_top)))rescued_pca <- prcomp(mixed_units, center = TRUE, scale. = TRUE)rescued_share <- rescued_pca$sdev^2 / sum(rescued_pca$sdev^2)rescued_top <- TopLoadings(rescued_pca$rotation)cat(sprintf("Scaled: PC1 share %.1f%%, shifted genes in the top ten: %d\n", 100 * rescued_share[1], sum(names(rescued_top) %in% shifted_genes)))Centered only: PC1 share 99.4%, top gene gene_49, loading 1.000Scaled: PC1 share 14.9%, shifted genes in the top ten: 10mixed_units = gene_matrix.copy()mixed_units["gene_49"] = 100 * mixed_units["gene_49"]mixed_pca = PCA()mixed_pca.fit(mixed_units)mixed_share = mixed_pca.explained_variance_ratio_mixed_top = top_loadings(mixed_pca, genes, count=1)print(f"Centered only: PC1 share {100 * mixed_share[0]:.1f}%, " f"top gene {mixed_top.index[0]}, " f"loading {abs(mixed_top.iloc[0]):.3f}")rescued_pca = PCA()rescued_pca.fit(StandardScaler().fit_transform(mixed_units))rescued_share = rescued_pca.explained_variance_ratio_rescued_top = top_loadings(rescued_pca, genes)print(f"Scaled: PC1 share {100 * rescued_share[0]:.1f}%, " "shifted genes in the top ten: " f"{rescued_top.index.isin(shifted_genes).sum()}")Centered only: PC1 share 99.4%, top gene gene_49, loading 1.000Scaled: PC1 share 14.9%, shifted genes in the top ten: 10With one column 100 times larger, the centered-only PCA reports on the units. PC1 carries 99.4% of the variance and is gene_49 alone, with an absolute loading of 1.000. The group difference is still in the data, pushed into the remaining 0.6%.
Scaling repairs it. The share of PC1 returns to 14.9% and the ten shifted genes lead it again, the same result as scaling the original matrix, because scaling removes the units. The prcomp() help page says that scaling is advisable in general, and for a table of mixed measurements, such as age in years beside a concentration in mmol/L, it is. State the choice in the methods either way.
Read a PCA with care
Section titled “Read a PCA with care”PCA does not use the group labels, so PC1 is whatever varies most. Name a component only after you have colored the scores by each known covariate and looked at its loadings.
The variance share depends on the preprocessing. The same matrix gave 27.3% without scaling and 14.9% with it. A share from one analysis cannot be compared with a share from another analysis that scaled or filtered the genes differently.
A score plot describes the samples and tests nothing. Two separate clouds on PC1 carry no p-value. Two overlapping clouds do not show that the groups are equal either, because a difference in a few genes can sit in a later component that the plot does not show.
Scientific references
Section titled “Scientific references”Jolliffe and Cadima, 2016 review PCA as an eigenvalue problem that builds uncorrelated variables of successively maximal variance, and describe variants of the method for other data types.
Further reading
Section titled “Further reading”The R prcomp reference documents center, scale., and the returned sdev, rotation, and x that this page reads. The scikit-learn PCA reference does the same for components_ and explained_variance_ratio_, and states that the input is centered but not scaled.
An Introduction to Statistical Learning has an unsupervised learning chapter with R and Python labs that derive the components and discuss scaling.
The FactoMineR figures lesson draws the scree plot, the correlation circle, the biplot, and the contributions from one PCA object.