limma
limma fits a linear model to every gene and moderates the variance of each gene toward a
common prior with empirical Bayes. voom() prepares RNA-seq counts for it by turning
them into log2 counts per million with a precision weight per observation. The examples
run on the airway dataset, eight samples from four donors with and without
dexamethasone. The design ~ cell + dex and the filter are the ones the
limma-voom guide uses, so the numbers here match that guide.
Quick reference
Section titled “Quick reference”| Task | Call |
|---|---|
| Counts container | DGEList(counts, samples, group, genes) |
| From a SummarizedExperiment | SE2DGEList(se) |
| Filter | filterByExpr(dge, group = group) |
| TMM factors | calcNormFactors(dge) or normLibSizes(dge) |
| Design | model.matrix(~ cell + dex, data = sample_sheet) |
| Log-CPM and weights | voom(dge, design, plot = TRUE) |
| Fit | lmFit(v, design) |
| Moderate | eBayes(fit) |
| Ranked genes | topTable(fit, coef = "dextrt", number = Inf) |
| Up, down, not significant | decideTests(fit, p.value = 0.05) |
| Define comparisons | makeContrasts(a = x - y, levels = design) |
| Apply comparisons | eBayes(contrasts.fit(fit, contrast_matrix)) |
| F-test over coefficients | topTable(fit, coef = c("a", "b")) or coef = NULL |
| Donor as a random block | duplicateCorrelation(v, design, block = cell) |
| Fold change threshold | treat(fit, fc = 1.5) and topTreat() |
| Gene set test | camera(v, index = ids2indices(sets, rownames(v)), design, contrast) |
| Sample quality weights | voomWithQualityWeights(dge, design) |
| Sample QC | plotMDS(v) |
| Remove a batch for plots | removeBatchEffect(log_cpm, batch, design) |
| Variance trend | plotSA(fit) |
| Fold change against mean | plotMD(fit, column, status) |
| Volcano | volcanoplot(fit, coef, highlight, names) |
| Column | Meaning |
|---|---|
logFC |
Log2 fold change for the coefficient or contrast |
AveExpr |
Mean log2 CPM over all samples |
t |
Moderated t statistic |
P.Value |
p-value of the moderated t test |
adj.P.Val |
Benjamini-Hochberg adjusted p-value |
B |
Log odds that the gene is differentially expressed, absent after treat() |
Load the data
Section titled “Load the data”options(digits = 3) keeps the printed tables inside 80 columns.
The count object comes from Michael Love’s airway 1.32.0 data package, which declares LGPL. It represents the Himes and colleagues experiment, deposited as GSE52778 and SRP033351. The source and license notice identifies the original object. This lesson derives its summaries and figures from that object.
library(limma)library(edgeR)library(airway)library(dplyr)library(tibble)library(ggplot2)library(ggrepel)
options(digits = 3)dir.create("outputs", showWarnings = FALSE)data(airway)sample_sheet <- as.data.frame(colData(airway))[, c("cell", "dex")]sample_sheet$dex <- relevel(sample_sheet$dex, ref = "untrt")sample_sheet cell dexSRR1039508 N61311 untrtSRR1039509 N61311 trtSRR1039512 N052611 untrtSRR1039513 N052611 trtSRR1039516 N080611 untrtSRR1039517 N080611 trtSRR1039520 N061011 untrtSRR1039521 N061011 trtThe dex factor in airway lists trt first. Without the relevel(), the coefficient
would be dexuntrt and every fold change would carry the wrong sign.
Build a DGEList
Section titled “Build a DGEList”DGEList() holds the counts, the sample sheet and an optional gene table. The gene
symbols in rowData(airway) ride along into every results table.
dge <- DGEList( counts = assay(airway, "counts"), samples = sample_sheet, group = sample_sheet$dex, genes = as.data.frame(rowData(airway))[, "gene_name", drop = FALSE])dim(dge)[1] 63677 8edgeR 4 also reads a SummarizedExperiment in one call with SE2DGEList(airway).
Filter low counts
Section titled “Filter low counts”filterByExpr() keeps genes with enough counts per million in at least as many samples
as the smallest group. keep.lib.sizes = FALSE recomputes the library sizes afterwards.
keep <- filterByExpr(dge, group = sample_sheet$dex)dge <- dge[keep, , keep.lib.sizes = FALSE]nrow(dge)[1] 15926The filter keeps 15,926 of the 63,677 genes.
Normalize with TMM
Section titled “Normalize with TMM”dge <- calcNormFactors(dge, method = "TMM")dge$samples[, c("group", "lib.size", "norm.factors")] group lib.size norm.factorsSRR1039508 untrt 20608402 1.055SRR1039509 trt 18783120 1.021SRR1039512 untrt 25311320 0.990SRR1039513 trt 15144524 0.948SRR1039516 untrt 24411867 1.031SRR1039517 trt 30776089 0.978SRR1039520 untrt 19094104 1.027SRR1039521 trt 21135511 0.954edgeR 4 renamed this step normLibSizes(). calcNormFactors() still works and returns the
same factors.
Design matrix
Section titled “Design matrix”design <- model.matrix(~ cell + dex, data = sample_sheet)colnames(design)[1] "(Intercept)" "cellN061011" "cellN080611" "cellN61311" "dextrt"voom() draws its mean-variance trend to the current device, so open a file device
around it.
png("outputs/limma-voom.png", width = 6, height = 5, units = "in", res = 150)v <- voom(dge, design, plot = TRUE)invisible(dev.off())
Each point is a gene and the red line is the fitted trend. Observations low on the count axis sit high on the curve and get small weights.
Fit and moderate
Section titled “Fit and moderate”lmFit() fits the model gene by gene with the voom weights. eBayes() shrinks the gene
variances toward a common prior.
fit <- lmFit(v, design)fit <- eBayes(fit)round(fit$df.prior, 2)[1] 5.83Each gene has 3 residual degrees of freedom in this design, 8 samples less 5 coefficients. The prior adds 5.83, so the moderated variance leans more on the common value than on the gene’s own estimate.
topTable
Section titled “topTable”topTable() ranks genes for one coefficient by p-value. The gene_name column comes
from the gene table in the DGEList.
topTable(fit, coef = "dextrt", number = 5) gene_name logFC AveExpr t P.Value adj.P.Val BENSG00000165995 CACNB2 3.28 3.68 33.8 1.20e-10 1.92e-06 14.3ENSG00000120129 DUSP1 2.94 6.65 28.4 5.57e-10 2.07e-06 13.7ENSG00000157214 STEAP2 1.97 6.79 27.6 7.23e-10 2.07e-06 13.5ENSG00000162493 PDPN 1.88 5.19 27.5 7.39e-10 2.07e-06 13.4ENSG00000189221 MAOA 3.33 5.95 26.8 9.26e-10 2.07e-06 13.2number = Inf returns every gene. Convert the table to a tibble for dplyr.
res_tbl <- topTable(fit, coef = "dextrt", number = Inf) |> rownames_to_column("gene_id") |> as_tibble()res_tbl |> filter(adj.P.Val < 0.05, abs(logFC) > 1) |> count(direction = if_else(logFC > 0, "up", "down"))# A tibble: 2 × 2 direction n <chr> <int>1 down 4682 up 518decideTests
Section titled “decideTests”decideTests() labels each gene as down, not significant or up for each coefficient.
dt <- decideTests(fit, p.value = 0.05)summary(dt)[, "dextrt"] Down NotSig Up 2432 10912 2582These are the 2,582 up and 2,432 down genes that the limma-voom guide reports. Add
lfc = 1 to require a 2-fold change as well.
Contrasts
Section titled “Contrasts”Without an intercept, the design has one column for each dex level, and
makeContrasts() states each comparison as arithmetic on the columns. The second
contrast compares two donors.
design_means <- model.matrix(~ 0 + dex + cell, data = sample_sheet)contrast_matrix <- makeContrasts( treatment = dextrt - dexuntrt, donors = cellN080611 - cellN61311, levels = design_means)contrast_matrix ContrastsLevels treatment donors dexuntrt -1 0 dextrt 1 0 cellN061011 0 0 cellN080611 0 1 cellN61311 0 -1contrasts.fit() turns the fitted coefficients into the contrasts, and eBayes() runs
again on the result.
fit_means <- lmFit(v, design_means)fit_contrasts <- eBayes(contrasts.fit(fit_means, contrast_matrix))summary(decideTests(fit_contrasts, p.value = 0.05))all.equal(unname(fit_contrasts$coefficients[, "treatment"]), unname(fit$coefficients[, "dextrt"])) treatment donorsDown 2324 1273NotSig 11086 13557Up 2516 1096[1] TRUEThe treatment contrast reproduces the dextrt fold changes exactly, yet it calls 2,516
up and 2,324 down genes against 2,582 and 2,432. The help page of contrasts.fit()
explains the gap. With precision weights and a design that is not orthogonal, the
standard errors it returns are approximate. Fit the comparison you report as a
coefficient of the design.
F-test across coefficients
Section titled “F-test across coefficients”Give topTable() several coefficients and it runs a moderated F-test, which asks whether
any of them differs from zero. Here the three donor coefficients ask which genes differ
between donors at all. On a contrast fit, coef = NULL tests every contrast at once.
donor_coefs <- c("cellN061011", "cellN080611", "cellN61311")donor_f <- topTable(fit, coef = donor_coefs, number = Inf)donor_f[1:5, c("gene_name", "AveExpr", "F", "adj.P.Val")]sum(donor_f$adj.P.Val < 0.05) gene_name AveExpr F adj.P.ValENSG00000123243 ITIH5 8.52 915 4.02e-07ENSG00000106565 TMEM176B 3.87 500 2.86e-06ENSG00000002933 TMEM176A 3.24 432 2.90e-06ENSG00000204941 PSG5 4.99 423 2.90e-06ENSG00000262902 RP11-750B16.1 1.30 394 2.90e-06[1] 33793,379 genes differ between at least two donors at an FDR of 0.05, with ITIH5 first. The
table has an F column and one log fold change column per coefficient in place of t.
Block on donor
Section titled “Block on donor”Instead of a fixed effect for each donor, duplicateCorrelation() estimates how
correlated samples from one donor are, and lmFit() takes the donor as a block.
design_dex <- model.matrix(~ dex, data = sample_sheet)corfit <- duplicateCorrelation(v, design_dex, block = sample_sheet$cell)round(corfit$consensus.correlation, 3)fit_block <- lmFit(v, design_dex, block = sample_sheet$cell, correlation = corfit$consensus.correlation)fit_block <- eBayes(fit_block)summary(decideTests(fit_block, p.value = 0.05))[, "dextrt"][1] 0.544 Down NotSig Up 2390 11020 2516Samples from one donor correlate at 0.544. The blocked fit calls 2,516 up and 2,390 down
genes, close to the fixed effect fit. The limma User’s Guide runs voom() a second time
with block and correlation and then estimates the correlation again; one pass is
shown here. A random block is the tool when some comparisons run within donors and
others between them, where a donor term in the design would absorb the second kind.
treat() tests whether the absolute fold change exceeds a threshold, rather than
filtering on fold change after the test.
fit_treat <- treat(fit, fc = 1.5)topTreat(fit_treat, coef = "dextrt", number = 5)summary(decideTests(fit_treat, p.value = 0.05))[, "dextrt"] gene_name logFC AveExpr t P.Value adj.P.ValENSG00000165995 CACNB2 3.28 3.68 27.8 3.50e-10 5.58e-06ENSG00000179593 ALOX15B 8.06 -1.48 24.3 1.40e-09 8.28e-06ENSG00000120129 DUSP1 2.94 6.65 22.7 1.99e-09 8.28e-06ENSG00000152583 SPARCL1 4.56 4.17 22.5 2.33e-09 8.28e-06ENSG00000189221 MAOA 3.33 5.95 22.1 2.60e-09 8.28e-06 Down NotSig Up 285 15277 364At a fold change threshold of 1.5, 364 genes test up and 285 down. ALOX15B enters the top five
with a log2 fold change of 8.06 on an average log2 CPM of -1.48, and the table has no B
column. Current limma takes the threshold as a fold change, fc = 1.5. Older code
passes lfc = log2(1.5), which gives the same test.
Gene set test with camera
Section titled “Gene set test with camera”camera() tests whether the genes of a set move together for one coefficient, and it
allows for correlation between the genes. The sets here come from GO through
org.Hs.eg.db and GO.db, so they need no network. The GOALL key includes the genes of
every child term.
The five sets use Gene Ontology annotations distributed through org.Hs.eg.db and GO.db. The Gene Ontology Consortium data policy supplies the CC BY 4.0 terms. This example selects five terms, maps their annotations to Ensembl identifiers, and removes missing and repeated identifiers before the test.
go_ids <- c("GO:0051384", "GO:0006954", "GO:0030198", "GO:0006260", "GO:0006412")go_genes <- AnnotationDbi::select( org.Hs.eg.db::org.Hs.eg.db, keys = go_ids, keytype = "GOALL", columns = "ENSEMBL")go_terms <- AnnotationDbi::select( GO.db::GO.db, keys = go_ids, keytype = "GOID", columns = "TERM")gene_sets <- split(go_genes$ENSEMBL, go_genes$GOALL) |> lapply(\(ids) unique(ids[!is.na(ids)]))names(gene_sets) <- go_terms$TERM[match(names(gene_sets), go_terms$GOID)]set_index <- ids2indices(gene_sets, rownames(v))camera(v, index = set_index, design = design, contrast = "dextrt") NGenes Direction PValue FDRresponse to glucocorticoid 78 Up 0.0321 0.160DNA replication 285 Down 0.4219 0.955inflammatory response 471 Up 0.5922 0.955translation 609 Up 0.8452 0.955extracellular matrix organization 194 Up 0.9551 0.955camera is a competitive test, so it compares each set with the rest of the genes.
Response to glucocorticoid is the one set that moves, up with a p-value of 0.032, but an
FDR of 0.16 over five sets does not pass 0.05. ids2indices() turns gene ID lists into
row positions in v, and mroast() is the self-contained alternative.
Sample quality weights
Section titled “Sample quality weights”voomWithQualityWeights() adds a weight per sample on top of the voom weights, so a
noisy library counts for less. The plot shows the voom trend and the sample weights.
png("outputs/limma-quality-weights.png", width = 10, height = 4.5, units = "in", res = 150)vq <- voomWithQualityWeights(dge, design, plot = TRUE)invisible(dev.off())
data.frame(sample_sheet, weight = vq$targets$sample.weights)fit_vq <- eBayes(lmFit(vq, design))summary(decideTests(fit_vq, p.value = 0.05))[, "dextrt"] cell dex weightSRR1039508 N61311 untrt 1.110SRR1039509 N61311 trt 1.128SRR1039512 N052611 untrt 0.962SRR1039513 N052611 trt 0.949SRR1039516 N080611 untrt 0.684SRR1039517 N080611 trt 0.680SRR1039520 N061011 untrt 1.357SRR1039521 N061011 trt 1.387 Down NotSig Up 2598 10585 2743Both samples from donor N080611, the donor that sits apart on the MDS plot, get a weight of 0.68. With the weights, the fit calls 2,743 up and 2,598 down genes, against 2,582 and 2,432 with voom alone.
MDS plot
Section titled “MDS plot”plotMDS() places samples by the leading log2 fold change between each pair, the root
mean square of the 500 largest differences for that pair. Widen xlim when the labels
run off the edge.
dex_colors <- c(untrt = "#4DBBD5", trt = "#E64B35")png("outputs/limma-mds.png", width = 6, height = 5, units = "in", res = 150)plotMDS(v, labels = sample_sheet$cell, col = dex_colors[as.character(sample_sheet$dex)], xlim = c(-2.5, 2.7))legend("bottomright", legend = names(dex_colors), text.col = dex_colors)invisible(dev.off())
Remove the donor effect for plots
Section titled “Remove the donor effect for plots”removeBatchEffect() subtracts the donor effect from the log2 CPM values. The design
argument protects the treatment effect from being removed with it.
log_cpm <- cpm(dge, log = TRUE)log_cpm_no_donor <- removeBatchEffect( log_cpm, batch = sample_sheet$cell, design = model.matrix(~ dex, data = sample_sheet))png("outputs/limma-remove-batch.png", width = 10, height = 4.5, units = "in", res = 150)sample_colors <- dex_colors[as.character(sample_sheet$dex)]par(mfrow = c(1, 2))plotMDS(log_cpm, pch = 16, cex = 1.5, col = sample_colors, main = "log2 CPM")plotMDS(log_cpm_no_donor, pch = 16, cex = 1.5, col = sample_colors, main = "Donor removed")legend("top", legend = names(dex_colors), col = dex_colors, pch = 16)invisible(dev.off())
SA plot
Section titled “SA plot”plotSA() draws the residual standard deviation of each gene against its mean, with the
eBayes() prior as the blue line.
png("outputs/limma-sa.png", width = 6, height = 5, units = "in", res = 150)plotSA(fit, main = "Residual SD against mean expression")invisible(dev.off())
The cloud has no trend with the mean, because the voom weights absorbed it.
MD plot
Section titled “MD plot”status colors the genes. Text labels give a readable legend, where the raw
decideTests() values would show as 1, 0 and -1.
md_status <- c("down", "not sig", "up")[dt[, "dextrt"] + 2]png("outputs/limma-md.png", width = 6, height = 5, units = "in", res = 150)plotMD(fit, column = "dextrt", status = md_status, values = c("up", "down"), hl.col = c("#E64B35", "#4DBBD5"))abline(h = 0, col = "grey40", lty = 2)invisible(dev.off())
Volcano plot
Section titled “Volcano plot”limma’s own volcanoplot(fit, coef = "dextrt", highlight = 8, names = ...) draws this
plot in base graphics. Its labels overlap when top genes sit close together, as STEAP2
and PDPN do here, so this version builds it from res_tbl with ggrepel.
top_genes <- res_tbl |> slice_min(P.Value, n = 8)volcano_plot <- ggplot(res_tbl, aes(logFC, -log10(P.Value))) + geom_point(aes(color = adj.P.Val < 0.05), size = 0.6, alpha = 0.5) + geom_text_repel(data = top_genes, aes(label = gene_name), size = 3.5, seed = 42) + scale_color_manual(values = c(`FALSE` = "grey70", `TRUE` = "#E64B35"), labels = c("not sig", "FDR < 0.05"), name = NULL) + labs(x = "log2 fold change", y = "-log10 p-value") + theme_minimal(base_size = 12)ggsave("outputs/limma-volcano.png", volcano_plot, width = 6, height = 4.5, dpi = 150, bg = "white")
See also
Section titled “See also”- limma-voom runs this analysis step by step and compares it with DESeq2.
- edgeR fits the same paired design with the edgeR quasi-likelihood F-test.
- DESeq2 & pyDESeq2 fits the same design with DESeq2.
- Batch in the Design shows what a batch term in the design does to the results.
Scientific references
Section titled “Scientific references”Himes and colleagues, 2014 report the airway experiment used here.
Chen and colleagues, 2025 describe edgeR version 4 and its differential analysis of sequencing count data.
Ritchie and colleagues, 2015 describe limma and its linear models for differential expression in microarray and RNA-seq data.
Further reading
Section titled “Further reading”The limma 3.68.5 source references include voom.Rd, contrasts.fit.Rd, duplicateCorrelation.Rd, treat.Rd, and camera.Rd. Read the contrast approximation note before comparing the two treatment tests. The correlation reference explains the repeated fit used for a donor block, while camera.Rd distinguishes competitive gene set tests from tests within one set.
The airway vignette records the count construction and sample design. The Gene Ontology citation policy explains attribution for the annotations used to construct the five gene sets.