About this page
Tutorial- What this page solves
- You have a gene expression matrix and a clinical measurement for each sample, such as fibrosis stage. You want to know which genes change together, which group of genes tracks disease severity, and which of them matter most.
- Who it is for
- Medical graduate students doing WGCNA for the first time. They can run R code but have not done a co-expression network analysis.
- What you will have
- You will have a filtered expression matrix, a soft-threshold plot, the module assignments, a module-trait correlation heatmap, a GS-MM scatter plot and a table of hub genes.
- Covers
- Starting from a GEO RNA-seq count matrix through filtering, transformation, outlier checks and network construction
- Choosing the soft threshold β and identifying co-expression modules
- Correlating modules with clinical traits and selecting hub genes
- Common errors, small sample sizes and very large gene sets (see the troubleshooting section and choices)
- Does not cover
- Co-expression networks from single-cell data (see the single-cell workflow)
- Functional enrichment of module genes (see differential and enrichment analysis)
- Wet-lab validation such as qPCR or immunohistochemistry
Main steps
Step 1 · Input matrix
Why this stepWGCNA only sees the matrix you give it, so the input decides the result. It needs samples in rows, genes in columns, and transformed values. Counts are the raw read counts from sequencing, and they cannot be used directly in WGCNA.
The example data is GEO dataset GSE130970: RNA-seq from liver biopsies of 78 patients with nonalcoholic fatty liver disease, with clinical scores such as fibrosis stage. First install WGCNA and its dependencies. WGCNA is on CRAN and its dependencies are on Bioconductor, so both sources are needed.
Then do three things: remove low-expression genes; apply the DESeq2 vst variance-stabilising transformation; and keep the 5000 genes with the highest MAD (median absolute deviation, a measure of variability).
The low-expression filter removes genes with a count below 10 in more than 90% of samples. In this example the number of genes falls from 39376 to 23337.
Genes are chosen by variability, not by the trait, because WGCNA is an unsupervised method; the trait is used later.
For FPKM or TPM data, use log2(x + 1) instead. The reasons for each transformation are in the input-data table in the reference section.
If counts are used directly, the network will be wrong; see the troubleshooting section.
# R >= 4.3; WGCNA 1.74 is on CRAN; its dependencies impute, preprocessCore and GO.db are on Bioconductor
install.packages("BiocManager")
BiocManager::install(c("impute", "preprocessCore", "GO.db", "AnnotationDbi",
"DESeq2", "org.Hs.eg.db"))
install.packages("WGCNA")# Load DESeq2 and other Bioconductor packages first and WGCNA last, so S4Vectors does not mask cor
suppressMessages({library(DESeq2); library(org.Hs.eg.db); library(WGCNA)})
options(stringsAsFactors = FALSE, timeout = 600)
acc <- "GSE130970" # 78 NAFLD liver biopsies, RNA-seq, with fibrosis stage and other histology scores
dir.create("geo", showWarnings = FALSE)
f_cnt <- file.path("geo", paste0(acc, "_raw_counts.tsv.gz"))
f_mat <- file.path("geo", paste0(acc, "_series_matrix.txt.gz"))
if (!file.exists(f_cnt)) download.file(paste0(
"https://www.ncbi.nlm.nih.gov/geo/download/?type=rnaseq_counts&acc=", acc,
"&format=file&file=", acc, "_raw_counts_GRCh38.p13_NCBI.tsv.gz"), f_cnt, mode = "wb")
if (!file.exists(f_mat)) download.file(paste0(
"https://ftp.ncbi.nlm.nih.gov/geo/series/GSE130nnn/", acc, "/matrix/", acc,
"_series_matrix.txt.gz"), f_mat, mode = "wb")
cnt <- as.matrix(read.delim(f_cnt, row.names = 1, check.names = FALSE)) # 39376 x 78, row names are Entrez IDs
# 1. Drop low-count genes: count < 10 in more than 90% of samples (the example in the official FAQ)
keep <- rowSums(cnt >= 10) >= 0.1 * ncol(cnt)
sym <- mapIds(org.Hs.eg.db, rownames(cnt), "SYMBOL", "ENTREZID")
cnt <- cnt[keep & !is.na(sym), ]
rownames(cnt) <- make.unique(sym[rownames(cnt)]) # 23337 genes
# 2. Variance-stabilizing transformation; never feed raw counts or un-logged FPKM into WGCNA
dds <- DESeqDataSetFromMatrix(cnt, data.frame(row.names = colnames(cnt), x = rep(1, ncol(cnt))), ~1)
expr <- assay(vst(dds, blind = TRUE))
# 3. Keep the top 5000 genes by MAD and transpose to rows = samples, columns = genes
datExpr <- t(expr[order(apply(expr, 1, mad), decreasing = TRUE)[1:5000], ])
dim(datExpr) # 78 5000
# Clinical traits: parse the characteristics rows of the Series Matrix
sm <- readLines(gzfile(f_mat))
row <- function(p) lapply(sm[startsWith(sm, p)], function(x) gsub('"', "", strsplit(x, "\t")[[1]][-1]))
ch <- row("!Sample_characteristics_ch1")
tr <- as.data.frame(lapply(ch, function(v) sub("^[^:]+: ", "", v)))
names(tr) <- sapply(ch, function(v) sub(":.*", "", v[1]))
rownames(tr) <- row("!Sample_geo_accession")[[1]]
tr <- tr[rownames(datExpr), ]
traits <- data.frame(fibrosis = as.numeric(tr$`fibrosis stage`),
NAS = as.numeric(tr$`nafld activity score`),
steatosis = as.numeric(tr$`steatosis grade`),
ballooning = as.numeric(tr$`cytological ballooning grade`),
inflammation = as.numeric(tr$`lobular inflammation grade`),
age = as.numeric(tr$`age at biopsy`),
male = as.numeric(tr$Sex == "M"), row.names = rownames(tr))Outlier samples
Why this stepOutlier samples have expression patterns clearly different from the others. They distort later correlation calculations, so find and remove them before building the network.
First draw a sample cluster tree and check for samples hanging alone at the edge. In this example the maximum merge height is 84.4 and no single sample is isolated.
When the tree is unclear, quantify with the standardised connectivity Z.k. Samples with very low connectivity are treated as outliers; a common cut-off is Z.k < -2.5.
In this example Z.k flags GSM3758009 (-6.14) and GSM3758047. After removing them, 76 samples remain.
In this example keeping the two samples still gives β = 7 and 14 modules. However, outliers have a larger effect in small datasets.
If the cluster tree shows two major branches, see the troubleshooting section.
gsg <- goodSamplesGenes(datExpr, verbose = 0); gsg$allOK # FALSE if genes have missing values or zero variance
sampleTree <- hclust(dist(datExpr), method = "average")
plot(sampleTree, cex = 0.6, main = "Sample clustering") # look for samples hanging off on their own
# Standardized connectivity Z.k: samples with very low connectivity in the sample network are outliers (common cutoff -2.5)
A <- adjacency(t(datExpr), type = "distance")
Zk <- as.numeric(scale(colSums(A) - 1))
rownames(datExpr)[Zk < -2.5] # GSE130970: GSM3758009 GSM3758047
datExpr <- datExpr[Zk >= -2.5, ]; traits <- traits[rownames(datExpr), ]
nSamples <- nrow(datExpr) # 76Soft threshold
Why this stepThe soft threshold β determines how a correlation is turned into a connection strength. WGCNA aims for a scale-free network, in which a few genes have many connections and most have few. pickSoftThreshold computes the scale-free fit R² for each candidate β; a higher R² means a closer fit.
The default RsquaredCut is 0.85 and the default networkType is unsigned. This example uses a signed network with bicor correlation; the β choice must match the network settings used later.
pickSoftThreshold returns the first β whose R² exceeds the threshold. In this example, β = 7.
If no β reaches the threshold, see choices: how to set the soft threshold.
allowWGCNAThreads(4) # if parallel runs fail inside RStudio, use disableWGCNAThreads()
powers <- c(1:10, seq(12, 20, 2))
sft <- pickSoftThreshold(datExpr, powerVector = powers, networkType = "signed",
corFnc = bicor, corOptions = list(maxPOutliers = 0.05),
RsquaredCut = 0.85, verbose = 0)
fi <- sft$fitIndices
data.frame(power = fi$Power, R2 = round(-sign(fi$slope) * fi$SFT.R.sq, 3), mean.k = round(fi$mean.k., 1))
beta <- sft$powerEstimate # GSE130970 (76 samples): 7
# If no power reaches the cutoff, use the empirical values from the official FAQ (December 2017 version)
if (is.na(beta)) {
n <- nSamples; signed <- TRUE
beta <- if (n < 20) 9 else if (n < 30) 8 else if (n < 40) 7 else 6
if (signed) beta <- beta * 2
}
par(mfrow = c(1, 2))
plot(fi$Power, -sign(fi$slope) * fi$SFT.R.sq, type = "n", xlab = "power", ylab = "signed R^2")
text(fi$Power, -sign(fi$slope) * fi$SFT.R.sq, fi$Power, col = "red"); abline(h = 0.85, col = "red")
plot(fi$Power, fi$mean.k., type = "n", xlab = "power", ylab = "mean connectivity")
text(fi$Power, fi$mean.k., fi$Power, col = "red")Module detection
Why this stepblockwiseModules uses β to convert correlations into adjacencies, then computes the topological overlap matrix (TOM), which measures how many neighbours two genes share. It clusters the genes hierarchically and cuts the tree into modules. Genes that join no module are placed in grey.
networkType and TOMType must match the β choice, so both are signed here. The correlation is bicor with maxPOutliers = 0.05, which caps the fraction of samples bicor may treat as outliers.
minModuleSize 30 requires each module to contain at least 30 genes. deepSplit 2 and mergeCutHeight 0.25 control how finely the tree is cut and when similar modules are merged. The parameters are explained in the reference section.
In this example all 5000 genes are processed in one block, with maxBlockSize set to 6000, larger than the gene count. For larger gene sets, see choices: many genes and limited memory.
net <- blockwiseModules(datExpr, power = beta,
networkType = "signed", TOMType = "signed", # networkType must match pickSoftThreshold
corType = "bicor", maxPOutliers = 0.05,
maxBlockSize = 6000, # larger than the gene count, so there is a single block
minModuleSize = 30, deepSplit = 2, mergeCutHeight = 0.25,
pamRespectsDendro = FALSE, numericLabels = TRUE, verbose = 3)
moduleColors <- labels2colors(net$colors)
table(moduleColors) # GSE130970: 14 modules, 1369 genes in grey
plotDendroAndColors(net$dendrograms[[1]], moduleColors[net$blockGenes[[1]]], "Module",
dendroLabels = FALSE, hang = 0.03, addGuide = TRUE, guideHang = 0.05)Module-trait
Why this stepEach module is summarised by its module eigengene (ME), the first principal component of the module expression matrix, which can be read as the overall expression level of the module. Correlating MEs with clinical traits shows which modules are related to disease.
Each cell of the heatmap shows the correlation coefficient and P value. Red means positive correlation and blue means negative.
In this example the yellow module correlates 0.58 with fibrosis stage, and the turquoise module correlates -0.67 with the NAS score (NAFLD activity score). Select modules by the absolute value of the correlation; negative correlations are equally informative.
Add potential confounders such as sex, age and batch to the trait table. How they affect interpretation is explained in the section on reading module-trait correlations.
MEs <- orderMEs(moduleEigengenes(datExpr, moduleColors)$eigengenes)
moduleTraitCor <- cor(MEs, traits, use = "p")
moduleTraitP <- corPvalueStudent(moduleTraitCor, nSamples)
textMatrix <- paste0(signif(moduleTraitCor, 2), "\n(", signif(moduleTraitP, 1), ")")
par(mar = c(6, 9, 3, 3))
labeledHeatmap(moduleTraitCor, xLabels = names(traits), yLabels = names(MEs), ySymbols = names(MEs),
colorLabels = FALSE, colors = blueWhiteRed(50), textMatrix = textMatrix,
setStdMargins = FALSE, cex.text = 0.6, zlim = c(-1, 1), main = "Module-trait relationships")
# bicor also works for binary or ordinal traits, but turn off robust handling of the trait:
# bicor(MEs, traits, maxPOutliers = 0.05, robustY = FALSE)Hub genes
Why this stepHub genes are the most connected core genes of a module. Two measures are used: MM (module membership, or kME, the correlation between a gene and the module eigengene) and GS (gene significance, the correlation between a gene and the trait).
In this example the yellow module (related to fibrosis) is screened with |MM| > 0.8 and |GS| > 0.2, giving 12 genes. The origin of these thresholds is explained in the section on GS thresholds and sample size.
kWithin is a gene's connectivity within its module. Genes can also be ranked by kWithin and the top ones taken. In this example the rank correlation between kWithin and MM is 0.95, so the two rankings nearly agree.
The number of genes selected by different thresholds is compared in the reference section.
module <- "yellow"; trait <- "fibrosis"
MM <- cor(datExpr, MEs[, paste0("ME", module)], use = "p")[, 1] # module membership (kME)
GS <- cor(datExpr, traits[[trait]], use = "p")[, 1] # gene significance
inMod <- moduleColors == module
verboseScatterplot(abs(MM[inMod]), abs(GS[inMod]), xlab = paste("MM in", module),
ylab = paste("GS for", trait), col = module, abline = TRUE)
abline(v = 0.8, h = 0.2, lty = 2)
# |GS| needed for two-sided P < 0.05 at sample size n
tq <- qt(0.975, nSamples - 2); sqrt(tq^2 / (tq^2 + nSamples - 2)) # 0.226 at n = 76
# Intramodular connectivity kWithin
adj <- adjacency(datExpr, power = beta, type = "signed",
corFnc = "bicor", corOptions = "maxPOutliers = 0.05")
kIM <- intramodularConnectivity(adj, moduleColors)
hub <- data.frame(gene = colnames(datExpr), MM = MM, GS = GS, kWithin = kIM$kWithin)[inMod, ]
hub <- hub[order(-hub$kWithin), ]
head(hub, 10)
subset(hub, abs(MM) > 0.8 & abs(GS) > 0.2) # GSE130970: 12 genes
cor(hub$kWithin, hub$MM, method = "spearman") # 0.95: the two rankings are almost identicalChoose by your situation
Choices
Use the table below to decide how to handle the R² threshold, the network type, and a β that never reaches the threshold.
The usual threshold is 0.85, the default of pickSoftThreshold. The official tutorial plot shows a 0.90 line; on the mouse liver data it selects β = 6 (R² 0.902). The FAQ uses 0.8 when checking whether the data have a problem. Take the first β where the curve levels off.
The FAQ recommends signed or signed hybrid networks. An unsigned network puts positively and negatively correlated genes in the same module, so the eigengene direction no longer matches each gene.
Use bicor as the correlation, with maxPOutliers = 0.05 or 0.10. Without it, when expression is strongly driven by a binary variable such as disease status, bicor treats one group of samples as outliers.
If no β reaches the threshold, the FAQ (updated December 2017) gives empirical values. For unsigned and signed hybrid networks: 9 for fewer than 20 samples, 8 for 20–30, 7 for 30–40, and 6 above 40. For signed networks: 18, 16, 14 and 12.
Before using an empirical β, rule out batch effects, outliers and differential-expression filtering. In this example, a signed network with β = 12 on 76 samples gives 13 modules and 1661 genes in grey. The strongest module-fibrosis correlation is 0.53, compared with 0.58 at β = 7.
The slope need not be close to -1
Some posts require the slope to be close to -1. Signed networks usually have steeper slopes: here, signed + bicor at β = 7 gives a slope of -2.67. The official function and tutorial select β by R² only.
Four combinations give different β values
For the same 78 samples, powerEstimate is 6 for unsigned + pearson, 7 for unsigned + bicor, 9 for signed + pearson and 8 for signed + bicor. A signed adjacency is (0.5 + 0.5 × cor)^β, which is denser than the unsigned one at the same β, so a larger β is needed.
| Situation | What to do |
|---|---|
| R² levels off and several β values exceed the threshold | Take the first β above the threshold, not a higher one |
| No β reaches the threshold, and batch, outliers and differential-expression filtering have been ruled out | Use the empirical β from the FAQ (see below) and state it in the paper |
| Comparing signed with unsigned | The two need different β values; choose β separately and do not mix them |
Sample size
Sample size affects whether a soft threshold can be found, how stable the modules are, and the GS threshold.
With few samples, the soft threshold often fails to reach the R² cut-off, and the significance bar for GS is higher: with 20 samples, |GS| must exceed 0.444 to be significant.
If the R² cut-off is still not reached, use the empirical β described in the soft-threshold choice and state it in the paper.
| Situation | Recommendation |
|---|---|
| Fewer than 15 samples | The official FAQ advises against WGCNA |
| 15 to 20 samples | Possible, but modules are less stable with fewer samples; state the sample size in the paper |
| 20 or more | Aim for this. More samples give more stable modules |
| Separate networks per group, such as sex or tissue (consensus analysis) | About 30 or more per group |
Memory and blocks
The TOM is a matrix of size genes × genes, so memory grows with the square of the gene count. Decide first whether to split the genes into blocks.
When the gene count exceeds maxBlockSize (default 5000), blockwiseModules first pre-clusters the genes into blocks with a k-means-like step, builds a network for each block, and merges similar modules at the end.
The cost of blocks is that the module membership of genes spanning blocks can be wrong. In this example, splitting 15000 genes into 4 blocks gives an adjusted Rand index (ARI, which measures agreement between two partitions, where 1 is identical) of only 0.42 against a single block.
In the single-block result for 15000 genes, the yellow module, which is related to fibrosis, falls mainly into 2 modules. In the block result it spreads across 3 modules.
The official tutorial compared blocks with a single block on 3600 probes and found them "very similar". That conclusion does not hold for tens of thousands of genes.
The official tutorial gives these memory rules of thumb: about 8000–10000 probes with 4 GB, about 20000 with 16 GB, and about 30000 with 32 GB. In this example, 20000 genes in one block finished on a 16 GB machine with a peak of 6.5 GB. The hard limit for maxBlockSize is sqrt(2^31), about 46340.
| Situation | What to do |
|---|---|
| Enough memory | Set maxBlockSize above the gene count so there is one block |
| Not enough memory | Reduce the gene count first. Keep the top 5000–10000 by MAD, which usually covers the main co-expression structure, and place all of them in one block |
| All genes are needed | Use a machine with more memory. If blocks are unavoidable, state how blocking affects module boundaries in the paper |
Validation
Modules and hub genes come from the same samples, which papers are often challenged for. Validation can be done entirely with public data.
Use modulePreservation to test whether the modules are preserved in an independent dataset. Zsummary above 10 means strong preservation, 2 to 10 moderate, and below 2 not preserved.
Then test whether the hub genes correlate with the same trait in the independent data. In this example, GSE135251 (216 patients) gives a Zsummary of 20.4 for the yellow module, which is strong preservation. Of 11 candidate hubs, 10 correlate significantly with fibrosis stage (Spearman rho 0.21–0.60), while ARPC5 does not (P = 0.096). The run took 157 seconds.
# External data processed the same way into a vst matrix (rows = samples, columns = genes): GSE135251, 216 samples
common <- intersect(colnames(datExpr), colnames(datExpr2))
mp <- modulePreservation(
list(ref = list(data = datExpr[, common]), test = list(data = datExpr2[, common])),
list(ref = setNames(moduleColors, colnames(datExpr))[common]),
referenceNetworks = 1, nPermutations = 50, networkType = "signed",
corFnc = "bicor", randomSeed = 1, maxGoldModuleSize = 300, maxModuleSize = 1000, verbose = 0)
z <- mp$preservation$Z$ref.ref$inColumnsAlsoPresentIn.test
z[, c("moduleSize", "Zsummary.pres")] # Zsummary > 10 strong, 2-10 moderate, < 2 not preservedHand it to an agent
Downloading, transforming, choosing β, building the network, plotting and external validation follow fixed steps, so an agent can run them. You still choose the dataset, define the traits and interpret the modules.
Example instruction: "Run WGCNA on GSE130970. Filter low-expression NCBI raw counts, apply vst, keep the top 5000 genes by MAD, and remove outliers with Z.k < -2.5. Use a signed network with bicor (maxPOutliers = 0.05) to choose β, then a single-block blockwiseModules (minModuleSize 30, mergeCutHeight 0.25). Build a module-trait heatmap against fibrosis, NAS, sex and age. For the most relevant module, output a GS-MM scatter plot and a hub table ranked by kWithin. Validate with modulePreservation on GSE135251 and test hub-fibrosis correlations there. Add a sensitivity analysis over deepSplit 0–4."
- 01
Data and preprocessing
Download the counts and Series Matrix, parse the traits, filter low expression, apply vst and MAD selection, and output the cluster tree and the outlier list.
- 02
Choose β and build the network
Run pickSoftThreshold and plot it, confirm networkType matches, decide between one block and several based on memory, and record run time and memory.
- 03
Module-trait and hub genes
Output the heatmap (with adjusted P values), the GS-MM scatter plot, the hub gene table and the module gene lists.
- 04
Validation and sensitivity analysis
Run module preservation and hub-trait correlation in an independent dataset, and compare whether key modules stay stable across deepSplit and β values.
- 05
Adversarial review
Check whether genes were filtered by differential expression, whether β and network type match, whether blocks were used, whether the |GS| threshold is significant for the sample size, and whether sex-related modules appear in the heatmap.
- Keep in the project: raw data, R scripts, sessionInfo, the β selection plots, the module assignment table, heatmaps and validation results.
- You still need to check: whether the traits are coded correctly, whether outlier removal is reasonable, and the biological interpretation of the chosen modules.
- Wet-lab validation such as qPCR or immunohistochemistry is done by you.
Concepts and judgment
Explanation
The sign of a correlation, the grey row and sex-related modules all change how the heatmap should be read.
Negatively correlated modules count too
The turquoise module correlates -0.67 with NAS, meaning the module as a whole goes down as the disease worsens. Rank modules by the absolute value of the correlation.
Put confounders in the heatmap
The pink and tan modules correlate with sex at -0.76 and 0.77 (P = 2.8e-16), so they are sex modules. Adding sex, age and batch to the trait table identifies such modules and prevents them being read as disease-related.
Multiple comparisons
With 14 modules and 7 traits there are 98 tests. In this example 33 have P < 0.05, and 17 remain after Bonferroni correction (0.05/98). Judge modules by both correlation strength and adjusted significance, and decide the main traits in advance.
The grey row is not interpreted
Grey is the set of genes that joined no module. Its ME correlation with a trait has no biological meaning, so it can be dropped from the plot.
Binary and ordinal traits
Binary 0/1 variables such as sex or group, and ordinal stages, can use Pearson correlation directly. When switching to bicor, add robustY = FALSE. In this example, Pearson and bicor(robustY = FALSE) differ by at most 0.15.
Explanation
|MM| > 0.8 and |GS| > 0.2 is a common combination in papers from China. Its basis depends on sample size.
Whether |GS| > 0.2 is significant depends on sample size. The |GS| needed for two-sided P < 0.05 is 0.444 with 20 samples, 0.361 with 30, 0.279 with 50, 0.226 with 76 and 0.197 with 100. 0.2 only becomes significant at 97 samples. With fewer samples, convert the threshold to the sample size, or require GS to be significant by its P value.
Peter Langfelder, the WGCNA author, answered on the Bioconductor support site that kME and intramodular connectivity usually give nearly the same ordering. The team often uses kME because it is easy to compute and has a P value. When several genes have high and similar kME, all can be treated as hubs; rank 3 and rank 7 are not substantively different.
In this example, the top 10 yellow-module genes by kWithin are TNFRSF12A, YWHAH, KPNA2, ARPC5, THBS2, ANXA2, TIGAR, ANXA2P2, LGALS3 and CCL20. They largely overlap with the 12 genes selected by |MM| > 0.8 and |GS| > 0.2.
Within the yellow module, the correlation between |MM| and |GS| is 0.715 (P = 1.5e-64). A high value means the core genes of the module are also the genes most strongly related to fibrosis. When this correlation is near zero, the hubs may not relate to the trait even if the module itself does.
Langfelder et al. (PLoS One, 2013) compared hub gene selection with standard meta-analysis. Hub genes from consensus modules were more useful for biological interpretation, and standard meta-analysis was no worse at validation. For biomarker discovery, give GS significance priority over MM.
Reference and appendix
Reference
The table lists common practice for each step, its basis, and the result in this example.
| Step | Practice | Basis or measurement |
|---|---|---|
| Sample size | Do not use fewer than 15; aim for 20 or more; about 30 or more per group when networks are built per category | Official FAQ (updated 2020-06-10) |
| Low-expression filter (RNA-seq) | Remove genes with count < 10 in more than 90% of samples | Example from the FAQ; GSE130970 drops from 39376 to 23337 genes |
| Transformation | Counts: DESeq2 vst or varianceStabilizingTransformation. FPKM, TPM or normalised counts: log2(x + 1) | FAQ; in this example the median per-sample correlation between vst and log2 CPM is 0.9985 |
| Gene number | Keep about the top 5000 by MAD or variance (commonly 3000–10000); the removed genes are the least variable | FAQ: mean- and variance-based filtering give similar results; the official liver tutorial uses 3600 |
| Do not filter by differential expression | WGCNA is unsupervised; building on differential genes leaves one or a few highly correlated modules and breaks the scale-free fit | FAQ; this example's measurements are in the troubleshooting section |
| Batch | Check batch first; use sva::ComBat for categorical batches and linear regression for continuous technical variables | FAQ |
Reference
| β | signed R² | Mean connectivity |
|---|---|---|
| 5 | 0.754 | 238.7 |
| 6 | 0.819 | 143.6 |
| 7 | 0.865 | 89.2 |
| 8 | 0.892 | 57.2 |
| 10 | 0.878 | 25.7 |
| 14 | 0.916 | 7.2 |
| 20 | 0.874 | 2.0 |
Reference
This page reproduces official tutorial I: mouse liver data with 3600 probes and 134 samples, β = 6, TOMType = "unsigned", minModuleSize = 30 and mergeCutHeight = 0.25. This gives 18 modules and 99 grey genes. Every module size matches the tutorial table, and the single-thread run took 7.9 seconds.
β also changes the number of modules. On the same data, β = 2, 3, 4 and 7 give 8, 8, 12 and 14 modules. There is no single correct module count. Reporting the parameters and running a sensitivity analysis is more defensible than tuning until a result looks right.
| Parameter | Default in 1.74 | Common value | Meaning and measured effect |
|---|---|---|---|
| networkType | "unsigned" | "signed" | Must match pickSoftThreshold. Using the signed β values (14, 20) on an unsigned network raises grey from 1903 to 4121 and 4659 genes (out of 5000) |
| TOMType | "signed" | Tutorial uses "unsigned" | For an unsigned network, signed TOM keeps the sign and then takes absolute values. Results are almost identical to "unsigned": the mouse liver data give the same 18 modules; for GSE130970 grey is 1903 in both and the largest module is 623 vs 622 |
| corType / maxPOutliers | "pearson" / 1 | "bicor" / 0.05 | Without maxPOutliers, expression patterns driven by a binary variable are treated as outliers by bicor |
| minModuleSize | min(20, genes/2) | 30 | 20/30/50/100 gives 16/14/11/9 modules |
| deepSplit | 2 | 2 | 0–4 gives 11/12/14/19/20 modules; a larger value cuts more finely and leaves less grey |
| mergeCutHeight | 0.15 | 0.25 | Modules whose eigengene correlation exceeds 1 − mergeCutHeight are merged. 0.15/0.25/0.35 gives 14/14/12 modules |
| maxBlockSize | 5000 | Above the gene count | If the gene count exceeds it, blocks are used; see the choice on many genes and limited memory |
| pamRespectsDendro | TRUE | Tutorial uses FALSE | In this example grey is 1360 vs 1369, a small difference |
| randomSeed | 54321 | Keep the default | Block pre-clustering uses random numbers. R 3.6.0 changed the generator; to reproduce old results use RNGkind("Mersenne-Twister", "Inversion", "Rounding") |
Reference
| Genes | maxBlockSize | Blocks | blockwiseModules time | Peak process memory | Result |
|---|---|---|---|---|---|
| 5000 | 6000 | 1 | 5.9 s | 1.6 GB | 14 modules |
| 10000 | 10000 | 1 | 18.3 s | 2.5 GB | 21 modules |
| 15000 | 15000 | 1 | 72 s | 3.9 GB | 27 modules, grey 3136 |
| 15000 | 5000 | 4 (4996/4819/2739/2446) | 29.8 s | 1.6 GB | 29 modules, grey 3864 |
| 20000 | 20000 | 1 | 196 s | 6.5 GB | 31 modules |
| 22490 | 23337 | 1 | — | Crashed at 5.5–7.1 GB | Crashed after the TOM calculation (segfault / bad binding access) |
Reference
| Module | Fibrosis stage | NAS score | Ballooning | Male |
|---|---|---|---|---|
| yellow (405 genes) | 0.58(P = 3.1e-8) | 0.69(P = 8.4e-12) | 0.57 | -0.12 |
| turquoise (798 genes) | -0.52 | -0.67 | -0.54 | -0.07 |
| pink (164 genes) | -0.02 | -0.16 | -0.11 | -0.76 |
| tan (98 genes) | -0.26 | -0.03 | -0.06 | 0.77 |
Reference
| Criterion | Selected from the yellow module (405 genes) | Note |
|---|---|---|
| |MM| > 0.8 and |GS| > 0.2 | 12 | Most common in papers from China; not in the official tutorial or FAQ |
| |MM| > 0.9 and |GS| > 0.2 | 0 | A slightly stricter threshold can leave none |
| |MM| > 0.8 and |GS| > 0.4 | 8 | |
| |MM| > 0.8 and |GS| > 0.5 | 5 | |
| Top 30 by kWithin | 30, including all 12 above | Spearman correlation between kWithin and MM is 0.95 |
Reference
The most common challenges to WGCNA papers are sample size and unvalidated hub genes. The table lists each challenge and the response.
| Challenge | Response |
|---|---|
| Small sample size | State the sample size and the FAQ guidance (at least 15, ideally 20 or more); if β misses the threshold, state the FAQ empirical value; convert the GS threshold to a significance bar for the sample size |
| Hub genes not validated | Run module preservation in an independent cohort and test hub-trait correlations. In this example, GSE135251 (216 patients) gives a Zsummary of 20.4 for yellow (above 10 is strong); 10 of 11 candidate hubs correlate significantly with fibrosis stage (Spearman rho 0.21–0.60), and ARPC5 does not (P = 0.096). The run took 157 seconds |
| Differential genes selected before WGCNA | Select genes by MAD or variance across all expressed genes; intersect differential genes with module genes after WGCNA |
| Unclear basis for β | Show both the R² and mean connectivity plots, and state RsquaredCut, networkType and the correlation method |
| Arbitrary parameters | Report minModuleSize, deepSplit, mergeCutHeight, maxBlockSize and whether blocks were used; add sensitivity analyses over deepSplit or β, and state whether key modules are stable |
| Module-trait correlation may reflect confounding | Add sex, age and batch to the heatmap; regress key modules on traits with adjustment for confounders |
| Bioinformatics analysis only | Validate hub genes by qPCR, immunohistochemistry or external data (TCGA, HPA, other GEO cohorts) |
Community experience
The points below come from WGCNA tutorials on CSDN, Jianshu, Tencent Cloud and Zhihu columns. Each has an error message or source code, and was reproduced or checked on this page.
The cor conflict and a temporary workaround
A CSDN post (2019) shows the blockwiseModules error "unused arguments (weights.x = NULL, weights.y = NULL, cosine = FALSE)". Running cor <- WGCNA::cor fixed it, and the post advises switching back to stats::cor afterwards. This page reproduced the same error; the cause is that IRanges and S4Vectors, which DESeq2 depends on, were loaded after WGCNA.
MAD filtering and empirical β
A Jianshu WGCNA tutorial from Shengxin Bioinformatics (2018) removes the lowest 25% of genes by MAD (with MAD at least 0.01), uses the FAQ table when no β fits, and recommends signed networks and bicor. Its module-trait code has the typo if (corType == "pearsoon"), so the Pearson branch never runs; copying it means bicor is used even when pearson is chosen.
Mismatched β and network type
A 2026 CSDN post on interpreting WGCNA results chooses β with networkType = "signed", but its blockwiseModules call leaves networkType at the default unsigned and sets TOMType = "unsigned". This page measured the mismatch: with the signed β on an unsigned network, grey holds 82%–93% of genes.
Log-transform FPKM first
A Tencent Cloud RNA-seq tutorial takes log2(x + 1) of FPKM, keeps the top 5000 genes by MAD and sets maxBlockSize to the gene count, which matches the FAQ. Its text says power = 16 but the code uses 15, so follow the code and rerun pickSoftThreshold. A highly ranked Zhihu tutorial filters FPKM by mean without log transformation, which is a counter-example.
Troubleshooting by error or symptom
Each entry is titled with the error or symptom you see, with its cause and fix together. Most errors below were reproduced on WGCNA 1.74; the rest come from the official FAQ.
unused arguments (weights.x = NULL, weights.y = NULL, cosine = FALSE)
Cause: The cor from WGCNA is masked by cor from another package. In this example, library(WGCNA) followed by library(DESeq2) puts the IRanges / S4Vectors cor first, which causes the error.
Fix: Load WGCNA last. Or run cor <- WGCNA::cor before blockwiseModules and switch back to stats::cor afterwards.
# Error: unused arguments (weights.x = NULL, weights.y = NULL, cosine = FALSE)
find("cor") # fails when IRanges / S4Vectors come before WGCNA
cor <- WGCNA::cor # set it temporarily, restore after blockwiseModules
net <- blockwiseModules(datExpr, power = beta, networkType = "signed", numericLabels = TRUE)
cor <- stats::cor
# Or restart R, load DESeq2 and the other packages first, then library(WGCNA) lastREAL() can only be applied to a 'numeric', not a 'integer'
Cause: The input is an integer matrix, usually because raw counts were used directly. Counts should not be used directly in WGCNA either.
Fix: Apply vst or a log transformation first. If you only need to change the type, use storage.mode(x) <- "double".
# Error: REAL() can only be applied to a 'numeric', not a 'integer'
storage.mode(datExpr) <- "double" # triggered by an integer matrix (e.g. raw counts), which should not be used anywayCounts used directly without vst, MAD-selected genes, and the soft-threshold R² stays low
Cause: MAD selection is dominated by highly expressed genes. In this example, the 5000 genes picked from raw counts overlap only 1296 with those picked after vst; the median count of the counts-selected genes is 1456, against 91.5 for vst-selected. The signed-network R² is still only 0.81 at β = 30.
Fix: Filter low-expression genes, apply DESeq2 vst, then select genes by MAD.
Genes selected by differential expression or trait correlation before building the network; module-trait correlations look too high
Cause: After keeping the top 2000 genes by correlation with fibrosis stage, the strongest module-fibrosis correlation rose from 0.58 to 0.73. The 0.73 comes from the selection itself and is not a result. The signed-network R² exceeded 0.85 only at β = 22, and grey kept only 10 genes. Selecting differential genes before WGCNA has the same problem.
Fix: Select genes by MAD or variance across all expressed genes, and intersect differential genes with module genes after WGCNA.
No error is raised, but the sample and gene counts do not match
Cause: The matrix is transposed, with genes in rows and samples in columns. goodSamplesGenes still returns TRUE, and the network is then built on samples as if they were genes.
Fix: Before analysis, check dim(datExpr); the number of rows should equal the number of samples.
The sample cluster tree has two major branches
Cause: The branches may reflect biological groups, or technical factors such as batch, sex or sequencing date.
Fix: Plot batch, sex and sequencing date under the tree to see where the branches come from. Then decide whether to remove samples, correct for the factor, or build separate networks.
The soft threshold does not reach 0.8 or 0.85
Cause: Three common causes: genes were selected by differential expression, there are batch effects or outliers, or the cluster tree has two major branches.
Fix: Rule out these three causes first. Once the differences are confirmed as biological, use the FAQ empirical β (see the soft-threshold choice). The FAQ considers a reasonable β range to be below 15 for unsigned and signed hybrid networks, and below 30 for signed networks. If R² still cannot reach 0.8 within that range while mean connectivity stays in the hundreds, a factor that shifts a subset of samples as a whole is often present. This page simulated 40% of genes shifted by +1.5 in half the samples: R² reached only 0.68 at β = 30, mean connectivity was still 26 at β = 30, and at β = 12 a single module of 2088 genes appeared.
The R² curve jumps sharply in the later part; R² drops and then rises again as β increases
Cause: Once mean connectivity drops below 1, the fit depends on only a few genes, so R² jumps. In this example the unsigned-pearson R² is 0.918 at β = 22, falls to 0.340 at β = 24, and returns to 0.937 at β = 26.
Fix: Look only at the first plateau before the curve becomes unstable, not at later values.
Grey holds more than half of the genes
Cause: β does not match networkType; β is so high that the network is too sparse; minModuleSize is too large; or there are few, noisy samples.
Fix: Check that pickSoftThreshold and blockwiseModules use the same networkType. With correct settings, grey is about 27% in this example.
β chosen with signed, but networkType was not set (default unsigned); grey holds 82%–93% of genes
Cause: β and network type do not match: a β chosen for a signed network was used on an unsigned one. In this example this mismatch moved most genes into grey.
Fix: Make networkType and TOMType identical in pickSoftThreshold and blockwiseModules, and choose β again.
Only one or two modules, or one very large module
Cause: Genes were selected by differential expression or trait; batch or tissue differences dominate expression; or β is too low.
Fix: Switch to MAD or variance filtering; plot the cluster tree to check for batches and correct them; use the FAQ to decide whether an empirical β is appropriate.
bicor warns zero MAD in variable 'y'
Cause: Most samples share one value, so the MAD is zero and bicor falls back to Pearson for that column.
Fix: For binary or ordinal traits, add robustY = FALSE when using bicor. In this example Pearson and bicor(robustY = FALSE) differ by at most 0.15.
malloc: *** mmap(size=...) failed ... can't allocate region (Mac)
Cause: The FAQ considers this message harmless.
Fix: Ignore it. If R crashes afterwards, treat it as a memory shortage; see the next entry.
R crashes (segfault, bad binding access)
Cause: Too many genes in one block. In this example, a single block of about 22500 genes on a 16 GB machine crashed after the TOM calculation.
Fix: Reduce the gene count or use a machine with more memory. If blocks are used, state the cost in the paper; see the choice on many genes and limited memory.
Gene names gain an X prefix
Cause: Converting the matrix to a data.frame adds an X to column names that start with a digit.
Fix: Keep the object as a matrix throughout, or read with check.names = FALSE.
could not find function, or GOenrichmentAnalysis reports deprecated
Cause: WGCNA did not load successfully, or GOenrichmentAnalysis was called; it was removed in 1.74 and now only returns a message.
Fix: Run library(WGCNA) and read the error. For enrichment, use clusterProfiler or the author's anRichment.
pickSoftThreshold fails in parallel inside RStudio, or reports thread 0 could not be started successfully. Error code: 11
Cause: A multithreading problem in a third-party GUI. The same error appears on a cluster where each job gets only one core.
Fix: Run disableWGCNAThreads() and run the step again.
References
- CRAN: WGCNA 1.74 — Current version and release date (2026-01-30)
- WGCNA ChangeLog — GOenrichmentAnalysis removed in 1.74; maxBlockSize limit; change in pre-clustering defaults
- WGCNA package FAQ (Langfelder & Horvath) — Sample size, gene filtering, RNA-seq transformation, signed networks and bicor, empirical β table, multithreading and common errors
- Official WGCNA tutorials (female mouse liver data) — Tutorial I data, one-step and blockwise construction, maxBlockSize memory guidance, module-trait and GS/MM
- Langfelder P, Horvath S. WGCNA: an R package for weighted correlation network analysis. BMC Bioinformatics, 2008 — Original method paper
- Langfelder P, Luo R, Oldham MC, Horvath S. Is my network module preserved and reproducible? PLoS Comput Biol, 2011 — modulePreservation and Zsummary thresholds
- Langfelder P, Mischel PS, Horvath S. When is hub gene selection better than standard meta-analysis? PLoS One, 2013 — Comparison of hub gene selection and marginal analysis
- Bioconductor support: WGCNA hub gene selection method — Langfelder's answer on kME versus kIM and hub rankings
- Hoang SA, et al. Gene expression predicts histological severity and reveals distinct molecular profiles of nonalcoholic fatty liver disease. Sci Rep, 2019 (GSE130970) — Dataset measured on this page
- GSE135251 (216 NAFLD liver biopsies) — External validation dataset on this page
- CSDN: WGCNA package errors in transcriptome analysis — Community post: cor conflict error message and the WGCNA::cor replacement
- Jianshu (Shengxin Baodian): A simple and complete WGCNA tutorial — Community post: MAD filtering, empirical β, signed networks and bicor; the pearsoon typo as a counterexample
- CSDN: WGCNA code and result interpretation — Community post: counterexample of mismatched β and network type
- Tencent Cloud: RNA-seq hands-on (11), WGCNA weighted gene co-expression network analysis — Community post: log2 of FPKM, top 5000 by MAD, single-block setting
- Zhihu column: Weighted gene co-expression network analysis (WGCNA) — Community post: counterexample with FPKM not log-transformed