Visualization and Pathways
A table of 1,153 tests is hard to read. This page draws the four figures that carry most of it for the Day 0 severity comparison of the Differential abundance page, then runs a Hallmark gene set test on the ranked t-statistics. The R tab uses ggplot2, pheatmap and fgsea. The Python tab uses matplotlib, seaborn and GSEApy.
The comparison again
Section titled “The comparison again”The page runs on its own, so the first block repeats the Day 0 comparison, LOD filter and
Welch t-tests of the differential page in short form, and finds the same 734 significant
assays. top_proteins keeps the best assay of each of the ten leading proteins, so the
four IL6 assays get one label.
The data below come from Bánk Fenyves’s version 2 deposit for Filbin and colleagues’ 2021 study, under CC BY 4.0. This lesson reshapes the NPX workbook, joins assay and clinical annotations, selects Day 0 COVID-positive subjects, and calculates the displayed comparisons.
suppressPackageStartupMessages({ library(readxl) library(dplyr) library(tidyr) library(OlinkAnalyze) library(ggplot2) library(ggrepel) library(pheatmap) library(fgsea) library(jsonlite)})
data_dir <- "/opt/data/mgh_covid_olink"dir.create("outputs", showWarnings = FALSE)severity_colours <- c(Severe = "#eb6834", `Non-severe` = "#2a78d6")
npx_wide <- read_excel(file.path(data_dir, "olink_proteomics.xlsx"), na = "NA")assays <- read_excel( file.path(data_dir, "supplemental_table_2_olink_assays.xlsx"), sheet = "2A-Olink-Assay", skip = 1)clinical <- read_excel(file.path(data_dir, "clinical_metadata.xlsx"), sheet = "Subject-level metadata")
# Day 0 samples of COVID-positive subjects. Acuity max 1 or 2 is severe.samples <- npx_wide |> filter(Day == "0") |> transmute(SampleID = `Public ID`, subject = as.numeric(sub("_.*", "", `Public ID`))) |> inner_join(clinical, by = c(subject = "Public ID")) |> filter(COVID == 1) |> transmute(SampleID, Severity = factor(if_else(`Acuity max` <= 2, "Severe", "Non-severe"), levels = c("Severe", "Non-severe")))
npx_long <- npx_wide |> filter(Day == "0") |> select(-Day) |> rename(SampleID = `Public ID`) |> pivot_longer(starts_with("OID"), names_to = "OlinkID", values_to = "NPX") |> inner_join(samples, by = "SampleID") |> inner_join(select(assays, OlinkID, Assay, UniProt, Panel, Panel_Version, LOD), by = "OlinkID") |> mutate(PlateID = NA_character_, QC_Warning = NA_character_, Panel_Version = as.character(Panel_Version))
# Keep an assay when at least half of the samples are above its LOD.detection <- npx_long |> group_by(OlinkID) |> summarise(above_lod = mean(NPX > LOD, na.rm = TRUE))npx_kept <- semi_join(npx_long, filter(detection, above_lod >= 0.5), by = "OlinkID")
welch <- olink_ttest(npx_kept, variable = "Severity", check_log = check_npx(npx_kept))cat("samples:", nrow(samples), " assays tested:", nrow(welch), " significant at FDR 0.05:", sum(welch$Adjusted_pval < 0.05), "\n")
# The best assay of each protein, for labels and panels.top_proteins <- welch |> distinct(Assay, .keep_all = TRUE) |> head(10)top_proteins |> transmute(Assay, OlinkID, estimate = round(estimate, 3), t = round(statistic, 2)) |> as.data.frame() |> print(row.names = FALSE)samples: 305 assays tested: 1153 significant at FDR 0.05: 734 Assay OlinkID estimate t KRT19 OID20596 1.887 10.23 IL6 OID20101 1.749 9.61 PTX3 OID20570 0.902 8.98 CHI3L1 OID20399 1.617 8.94 TRIAP1 OID21403 1.098 8.87 LTBP2 OID20254 1.025 8.82 IL1RL1 OID20250 1.158 8.78 POLR2F OID21283 0.900 8.79 AREG OID21357 1.196 8.61 MAPK9 OID20557 0.723 8.45import json
import gseapy as gpimport matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport seaborn as snsfrom matplotlib.lines import Line2Dfrom scipy import statsfrom scipy.cluster.hierarchy import fclusterfrom statsmodels.stats.multitest import multipletests
DATA_DIR = "/opt/data/mgh_covid_olink"SEVERITY_COLOURS = {"Severe": "#eb6834", "Non-severe": "#2a78d6"}
npx_wide = pd.read_excel(f"{DATA_DIR}/olink_proteomics.xlsx")assays = pd.read_excel( f"{DATA_DIR}/supplemental_table_2_olink_assays.xlsx", sheet_name="2A-Olink-Assay", skiprows=1,)clinical = pd.read_excel( f"{DATA_DIR}/clinical_metadata.xlsx", sheet_name="Subject-level metadata",).rename(columns={"Public ID": "subject"})
# Day 0 samples of COVID-positive subjects. Acuity max 1 or 2 is severe.day0 = npx_wide[npx_wide["Day"].astype(str) == "0"].copy()day0["subject"] = day0["Public ID"].str.split("_").str[0].astype(int)samples = day0[["Public ID", "subject"]].merge(clinical, on="subject")samples = samples[samples["COVID"] == 1].reset_index(drop=True)samples = pd.DataFrame({ "sample_id": samples["Public ID"], "severity": np.where(samples["Acuity max"] <= 2, "Severe", "Non-severe"),})is_severe = (samples["severity"] == "Severe").to_numpy()
olink_ids = [column for column in npx_wide if column.startswith("OID")]npx = day0.set_index("Public ID").loc[samples["sample_id"], olink_ids]lod = assays.set_index("OlinkID").loc[olink_ids, "LOD"]
# Keep an assay when at least half of the samples are above its LOD.above_lod = (npx > lod).where(npx.notna()).mean()npx = npx.loc[:, above_lod >= 0.5]
welch_result = stats.ttest_ind( npx.to_numpy()[is_severe], npx.to_numpy()[~is_severe], equal_var=False, nan_policy="omit",)welch = pd.DataFrame({ "OlinkID": npx.columns, "estimate": (npx[is_severe].mean() - npx[~is_severe].mean()).to_numpy(), "statistic": welch_result.statistic, "p_value": welch_result.pvalue,})welch["fdr"] = multipletests(welch["p_value"], method="fdr_bh")[1]welch = welch.merge(assays[["OlinkID", "Assay", "LOD"]], on="OlinkID")welch = welch.sort_values("p_value", kind="stable").reset_index(drop=True)print("samples:", len(samples), " assays tested:", len(welch), " significant at FDR 0.05:", int((welch["fdr"] < 0.05).sum()))
# The best assay of each protein, for labels and panels.top_proteins = welch.drop_duplicates("Assay").head(10)print(top_proteins[["Assay", "OlinkID"]] .assign(estimate=top_proteins["estimate"].round(3), t=top_proteins["statistic"].round(2)) .to_string(index=False))samples: 305 assays tested: 1153 significant at FDR 0.05: 734 Assay OlinkID estimate t KRT19 OID20596 1.887 10.23 IL6 OID20101 1.749 9.61 PTX3 OID20570 0.902 8.98CHI3L1 OID20399 1.617 8.94TRIAP1 OID21403 1.098 8.87 LTBP2 OID20254 1.025 8.82IL1RL1 OID20250 1.158 8.78POLR2F OID21283 0.900 8.79 AREG OID21357 1.196 8.61 MAPK9 OID20557 0.723 8.45Volcano plot
Section titled “Volcano plot”A volcano plot puts the effect on the x axis, here the difference in mean NPX, and the
evidence on the y axis as the negative log10 of the p-value. Benjamini-Hochberg fixes no
p-value threshold in advance, so the dashed line sits at the largest raw p-value that still
passes FDR 0.05. olink_volcano_plot() from OlinkAnalyze draws a similar plot in one call,
but its dotted line marks a raw p-value of 0.05, which is a different and looser cut.
# The largest p-value that still passes FDR 0.05 marks the cut.fdr_cut <- max(welch$p.value[welch$Adjusted_pval < 0.05])volcano_data <- welch |> mutate(direction = case_when( Adjusted_pval >= 0.05 ~ "not significant", estimate > 0 ~ "higher in severe", TRUE ~ "lower in severe" ))count(volcano_data, direction)cat("FDR 0.05 cut at p =", signif(fdr_cut, 3), "\n")
volcano <- ggplot(volcano_data, aes(estimate, -log10(p.value), colour = direction)) + geom_point(size = 1.4, alpha = 0.8) + geom_hline(yintercept = -log10(fdr_cut), linetype = "dashed", colour = "#52514e") + geom_text_repel(data = top_proteins, aes(estimate, -log10(p.value), label = Assay), inherit.aes = FALSE, size = 3.2, seed = 1, min.segment.length = 0) + scale_colour_manual(values = c( `higher in severe` = "#eb6834", `lower in severe` = "#2a78d6", `not significant` = "#c3c2b7" )) + labs(x = "Severe minus non-severe, NPX", y = "-log10 p-value", colour = NULL, title = "Welch t-tests, Day 0, 1,153 Olink Explore assays") + theme_minimal(base_size = 11) + theme(legend.position = "top", panel.grid.minor = element_blank())ggsave("outputs/olink-visualization_volcano_r.png", volcano, width = 7, height = 5.5, dpi = 120, bg = "white")# A tibble: 3 × 2 direction n <chr> <int>1 higher in severe 6872 lower in severe 473 not significant 419FDR 0.05 cut at p = 0.0317
def spread_labels(positions, min_gap): """Move label positions apart so that no two are closer than min_gap.
Args: positions: Label heights, sorted from the top down. min_gap: The smallest vertical distance between two labels.
Returns: list: The new label heights, from the top down. """ spaced = [] for position in positions: if spaced and spaced[-1] - position < min_gap: position = spaced[-1] - min_gap spaced.append(position) return spaced
fdr_cut = welch.loc[welch["fdr"] < 0.05, "p_value"].max()direction = np.select( [welch["fdr"] >= 0.05, welch["estimate"] > 0], ["not significant", "higher in severe"], default="lower in severe",)print(pd.Series(direction).value_counts().sort_index().to_string())print(f"FDR 0.05 cut at p = {fdr_cut:.3g}")
direction_colours = { "higher in severe": "#eb6834", "lower in severe": "#2a78d6", "not significant": "#c3c2b7",}figure, ax = plt.subplots(figsize=(7, 5.5))for name, colour in direction_colours.items(): subset = welch[direction == name] ax.scatter(subset["estimate"], -np.log10(subset["p_value"]), s=10, color=colour, alpha=0.8, label=name, linewidths=0)ax.axhline(-np.log10(fdr_cut), linestyle="--", color="#52514e", linewidth=1)# Labels sit in two columns, beside the right edge and left of the cloud.labels = top_proteins.assign(y=-np.log10(top_proteins["p_value"]))labels = labels.sort_values("y", ascending=False)columns = [(labels[labels["estimate"] >= 1.5], 2.0, "left"), (labels[labels["estimate"] < 1.5], 0.4, "right")]for column_rows, x_text, align in columns: heights = spread_labels(column_rows["y"].tolist(), 0.9) for row, y_text in zip(column_rows.itertuples(), heights): ax.annotate(row.Assay, (row.estimate, row.y), xytext=(x_text, y_text), textcoords="data", fontsize=8, ha=align, va="center", arrowprops={"arrowstyle": "-", "color": "#898781", "linewidth": 0.6})ax.set_xlim(right=2.35)ax.set_xlabel("Severe minus non-severe, NPX")ax.set_ylabel("-log10 p-value")ax.set_title("Welch t-tests, Day 0, 1,153 Olink Explore assays", loc="left")ax.legend(frameon=False, loc="lower right")ax.grid(color="#e1e0d9", linewidth=0.6)ax.set_axisbelow(True)ax.spines[["top", "right"]].set_visible(False)figure.tight_layout()figure.savefig("outputs/olink-visualization_volcano_python.png", dpi=120)higher in severe 687lower in severe 47not significant 419FDR 0.05 cut at p = 0.0317
The FDR line sits at p = 0.0317. The plot is lopsided: 687 significant assays rise in severe patients and 47 fall, and the falls stay close to zero next to the rises. Severe COVID-19 raises many plasma proteins at once. Keep that in mind for the gene set test below, which ranks proteins against each other.
Heatmap of the top proteins
Section titled “Heatmap of the top proteins”The heatmap shows the 30 leading proteins across all 305 samples. Each row is scaled to a mean of 0 and a standard deviation of 1, so a color says where a sample sits against the other samples for that protein, not its NPX. Rows and columns are clustered with complete linkage on Euclidean distance, the pheatmap default, and the Python call is set to match. The last lines cut the sample tree into two branches and count the patients in each.
heatmap_ids <- welch |> distinct(Assay, .keep_all = TRUE) |> head(30)heat <- npx_kept |> filter(OlinkID %in% heatmap_ids$OlinkID) |> select(Assay, SampleID, NPX) |> pivot_wider(names_from = SampleID, values_from = NPX)heat_matrix <- as.matrix(heat[, samples$SampleID])rownames(heat_matrix) <- heat$Assay
# Scale each protein to mean 0 and standard deviation 1 across samples.z <- t(scale(t(heat_matrix)))severe_cols <- samples$Severity == "Severe"cat("proteins:", nrow(z), " samples:", ncol(z), " missing values:", sum(is.na(z)), "\n")cat("mean z, severe:", round(mean(z[, severe_cols]), 4), " non-severe:", round(mean(z[, !severe_cols]), 4), "\n")
annotation <- data.frame(Severity = samples$Severity, row.names = samples$SampleID)heatmap_plot <- pheatmap( pmin(pmax(z, -3), 3), color = colorRampPalette(c("#2a78d6", "#f0efec", "#e34948"))(101), breaks = seq(-3, 3, length.out = 102), clustering_distance_rows = "euclidean", clustering_distance_cols = "euclidean", clustering_method = "complete", annotation_col = annotation, annotation_colors = list(Severity = severity_colours), show_colnames = FALSE, fontsize_row = 8, border_color = NA, main = "Top 30 proteins, z-score of NPX, 305 Day 0 samples", silent = TRUE)ggsave("outputs/olink-visualization_heatmap_r.png", heatmap_plot$gtable, width = 9, height = 6.5, dpi = 120, bg = "white")
# Cut the sample tree in two and call the branch with the higher mean z high.branch <- cutree(heatmap_plot$tree_col, k = 2)[samples$SampleID]high_branch <- which.max(tapply(colMeans(z), branch, mean))branch_table <- table(branch = if_else(branch == high_branch, "high", "low"), severity = samples$Severity)branch_tableproteins: 30 samples: 305 missing values: 0mean z, severe: 0.6003 non-severe: -0.3338 severitybranch Severe Non-severe high 78 35 low 31 161
heatmap_ids = welch.drop_duplicates("Assay").head(30)heat = npx[heatmap_ids["OlinkID"]].Theat.index = heatmap_ids["Assay"]
# Scale each protein to mean 0 and standard deviation 1 across samples.z = heat.sub(heat.mean(axis=1), axis=0).div(heat.std(axis=1), axis=0)print("proteins:", z.shape[0], " samples:", z.shape[1], " missing values:", int(z.isna().sum().sum()))print(f"mean z, severe: {z.loc[:, is_severe].to_numpy().mean():.4f}" f" non-severe: {z.loc[:, ~is_severe].to_numpy().mean():.4f}")
column_colours = pd.Series( samples["severity"].map(SEVERITY_COLOURS).to_numpy(), index=z.columns, name="Severity",)grid = sns.clustermap( z.clip(-3, 3), method="complete", metric="euclidean", cmap=sns.blend_palette(["#2a78d6", "#f0efec", "#e34948"], as_cmap=True), vmin=-3, vmax=3, col_colors=column_colours, xticklabels=False, yticklabels=True, figsize=(9, 6.5), cbar_pos=(0.02, 0.8, 0.02, 0.15),)grid.ax_heatmap.set_xlabel("")grid.ax_heatmap.set_ylabel("")grid.ax_heatmap.tick_params(axis="y", labelsize=8)grid.figure.suptitle("Top 30 proteins, z-score of NPX, 305 Day 0 samples", x=0.5, y=1.0)grid.figure.legend( handles=[Line2D([0], [0], marker="s", linestyle="", color=colour, label=name) for name, colour in SEVERITY_COLOURS.items()], frameon=False, loc="upper right", ncols=2, bbox_to_anchor=(0.99, 0.95),)grid.savefig("outputs/olink-visualization_heatmap_python.png", dpi=120)
# Cut the sample tree in two and call the branch with the higher mean z high.branch = fcluster(grid.dendrogram_col.linkage, t=2, criterion="maxclust")high_branch = pd.Series(z.mean(axis=0).to_numpy()).groupby(branch).mean()high_branch = high_branch.idxmax()branch_table = pd.crosstab( np.where(branch == high_branch, "high", "low"), samples["severity"].to_numpy(), rownames=["branch"], colnames=["severity"],)print(branch_table)proteins: 30 samples: 305 missing values: 0mean z, severe: 0.6003 non-severe: -0.3338severity Non-severe Severebranchhigh 35 78low 161 31
The high branch holds 78 severe and 35 non-severe patients, and the low branch holds 31 severe and 161 non-severe ones. Most severe patients share a raised profile across all 30 proteins, but 31 of them do not, and 35 non-severe patients look like the severe majority. Filbin et al. found the same heterogeneity, with several distinct clusters of severe patients on their Day 0 severity proteins. One caution applies to any heatmap of this kind. The 30 proteins were picked because they separate the groups in these same samples, so the picture cannot serve as evidence that they separate them.
PCA of the Day 0 samples
Section titled “PCA of the Day 0 samples”A PCA uses every assay and no labels. Each assay with no missing value is centered and scaled to unit variance, the components come from all of them, and severity only colors the points afterwards. The sign of a component is arbitrary, so both tabs turn each one to make the severe mean positive, which makes the two figures match.
pca_input <- npx_kept |> select(OlinkID, SampleID, NPX) |> pivot_wider(names_from = OlinkID, values_from = NPX)pca_matrix <- as.matrix(pca_input[, -1])rownames(pca_matrix) <- pca_input$SampleIDpca_matrix <- pca_matrix[samples$SampleID, ]# prcomp() needs complete columns, so drop the assays with a missing NPX.pca_matrix <- pca_matrix[, colSums(is.na(pca_matrix)) == 0]
pca <- prcomp(pca_matrix, center = TRUE, scale. = TRUE)variance <- pca$sdev^2 / sum(pca$sdev^2)scores <- as.data.frame(pca$x[, 1:2])# The sign of a component is arbitrary. Point both so the severe mean is# positive, which the Python tab does too.signs <- sign(colMeans(scores[samples$Severity == "Severe", ]))scores <- sweep(scores, 2, signs, "*")scores$Severity <- samples$Severity
cat("assays in the PCA:", ncol(pca_matrix), "\n")cat("variance explained, PC1 to PC5:", sprintf("%.2f%%", 100 * variance[1:5]), "\n")scores |> group_by(Severity) |> summarise(PC1 = round(mean(PC1), 3), PC2 = round(mean(PC2), 3)) |> as.data.frame()
pca_plot <- ggplot(scores, aes(PC1, PC2, colour = Severity)) + geom_point(size = 1.8, alpha = 0.8) + scale_colour_manual(values = severity_colours) + labs(x = sprintf("PC1, %.1f%% of variance", 100 * variance[1]), y = sprintf("PC2, %.1f%% of variance", 100 * variance[2]), colour = NULL, title = "PCA of 305 Day 0 samples") + theme_minimal(base_size = 11) + theme(legend.position = "top", panel.grid.minor = element_blank())ggsave("outputs/olink-visualization_pca_r.png", pca_plot, width = 6.5, height = 5.5, dpi = 120, bg = "white")assays in the PCA: 1152variance explained, PC1 to PC5: 28.85% 11.60% 6.58% 4.95% 3.98% Severity PC1 PC21 Severe 8.609 0.0952 Non-severe -4.788 -0.053
# Complete columns only, then scale each assay to unit variance.pca_matrix = npx.loc[:, npx.notna().all()]scaled = (pca_matrix - pca_matrix.mean()) / pca_matrix.std(ddof=1)u, singular, vt = np.linalg.svd(scaled.to_numpy(), full_matrices=False)variance = singular**2 / np.sum(singular**2)scores = u[:, :2] * singular[:2]# The sign of a component is arbitrary. Point both so the severe mean is# positive, as in the R tab.scores = scores * np.sign(scores[is_severe].mean(axis=0))scores = pd.DataFrame(scores, columns=["PC1", "PC2"])scores["severity"] = samples["severity"]
print("assays in the PCA:", pca_matrix.shape[1])print("variance explained, PC1 to PC5:", " ".join(f"{100 * value:.2f}%" for value in variance[:5]))print(scores.groupby("severity")[["PC1", "PC2"]].mean().round(3))
figure, ax = plt.subplots(figsize=(6.5, 5.5))for name, colour in SEVERITY_COLOURS.items(): subset = scores[scores["severity"] == name] ax.scatter(subset["PC1"], subset["PC2"], s=16, color=colour, alpha=0.8, label=name, linewidths=0)ax.set_xlabel(f"PC1, {100 * variance[0]:.1f}% of variance")ax.set_ylabel(f"PC2, {100 * variance[1]:.1f}% of variance")ax.set_title("PCA of 305 Day 0 samples", loc="left")ax.legend(frameon=False, loc="upper left", ncols=2)ax.grid(color="#e1e0d9", linewidth=0.6)ax.set_axisbelow(True)ax.spines[["top", "right"]].set_visible(False)figure.tight_layout()figure.savefig("outputs/olink-visualization_pca_python.png", dpi=120)assays in the PCA: 1152variance explained, PC1 to PC5: 28.85% 11.60% 6.58% 4.95% 3.98% PC1 PC2severityNon-severe -4.788 -0.053Severe 8.609 0.095
PC1 explains 28.85% of the variance across 1,152 assays and PC2 explains 11.60%. Severe patients lean toward positive PC1, with a mean score of 8.609 against -4.788 for non-severe patients, while PC2 hardly separates them. The overlap is wide. The largest axis of variation in Day 0 plasma is one on which severe patients score higher, and it is not a clean split.
Boxplots of the top proteins
Section titled “Boxplots of the top proteins”A boxplot shows the spread, the overlap and the values near the LOD that a mean difference hides. The dashed line is the assay LOD, and the table gives the share of each group below it.
box_ids <- head(top_proteins, 6)box_data <- npx_kept |> filter(OlinkID %in% box_ids$OlinkID) |> mutate(Assay = factor(Assay, levels = box_ids$Assay))box_summary <- box_data |> group_by(Assay, Severity) |> summarise(median = median(NPX, na.rm = TRUE), below_lod = mean(NPX < LOD, na.rm = TRUE), .groups = "drop")box_summary |> mutate(median = sprintf("%.3f", median), below_lod = sprintf("%.3f", below_lod)) |> as.data.frame() |> print(row.names = FALSE)
box_plot <- ggplot(box_data, aes(Severity, NPX, fill = Severity)) + geom_boxplot(outlier.size = 0.8, width = 0.6, alpha = 0.85) + geom_hline(data = distinct(box_data, Assay, LOD), aes(yintercept = LOD), linetype = "dashed", colour = "#52514e") + facet_wrap(~ Assay, scales = "free_y", nrow = 2) + scale_fill_manual(values = severity_colours) + labs(x = NULL, y = "NPX", fill = NULL, title = "Top six proteins at Day 0, dashed line at the assay LOD") + theme_minimal(base_size = 11) + theme(legend.position = "none", panel.grid.minor = element_blank())ggsave("outputs/olink-visualization_boxplots_r.png", box_plot, width = 8, height = 5.5, dpi = 120, bg = "white") Assay Severity median below_lod KRT19 Severe 4.290 0.037 KRT19 Non-severe 2.462 0.117 IL6 Severe 6.718 0.000 IL6 Non-severe 5.395 0.010 PTX3 Severe 6.359 0.000 PTX3 Non-severe 5.541 0.000 CHI3L1 Severe 4.643 0.073 CHI3L1 Non-severe 2.716 0.418 TRIAP1 Severe 3.397 0.000 TRIAP1 Non-severe 2.333 0.000 LTBP2 Severe 5.388 0.000 LTBP2 Non-severe 4.323 0.000
box_ids = top_proteins.head(6)figure, axes = plt.subplots(2, 3, figsize=(8, 5.5))box_rows = []for ax, row in zip(axes.ravel(), box_ids.itertuples()): groups = [npx.loc[samples["severity"].to_numpy() == name, row.OlinkID] .dropna() for name in SEVERITY_COLOURS] for name, group in zip(SEVERITY_COLOURS, groups): box_rows.append([row.Assay, name, group.median(), (group < row.LOD).mean()]) parts = ax.boxplot(groups, tick_labels=list(SEVERITY_COLOURS), widths=0.6, patch_artist=True, flierprops={"markersize": 2}) for patch, colour in zip(parts["boxes"], SEVERITY_COLOURS.values()): patch.set_facecolor(colour) patch.set_alpha(0.85) for median_line in parts["medians"]: median_line.set_color("#0b0b0b") ax.axhline(row.LOD, linestyle="--", color="#52514e", linewidth=1) ax.set_title(row.Assay, fontsize=10) ax.grid(axis="y", color="#e1e0d9", linewidth=0.6) ax.set_axisbelow(True) ax.spines[["top", "right"]].set_visible(False)for ax in axes[:, 0]: ax.set_ylabel("NPX")figure.suptitle("Top six proteins at Day 0, dashed line at the assay LOD", x=0.02, ha="left")figure.tight_layout()figure.savefig("outputs/olink-visualization_boxplots_python.png", dpi=120)
box_summary = pd.DataFrame( box_rows, columns=["Assay", "Severity", "median", "below_lod"])print(box_summary.to_string( index=False, formatters={"median": "{:.3f}".format, "below_lod": "{:.3f}".format},)) Assay Severity median below_lod KRT19 Severe 4.290 0.037 KRT19 Non-severe 2.462 0.117 IL6 Severe 6.718 0.000 IL6 Non-severe 5.395 0.010 PTX3 Severe 6.359 0.000 PTX3 Non-severe 5.541 0.000CHI3L1 Severe 4.643 0.073CHI3L1 Non-severe 2.716 0.418TRIAP1 Severe 3.397 0.000TRIAP1 Non-severe 2.333 0.000 LTBP2 Severe 5.388 0.000 LTBP2 Non-severe 4.323 0.000
CHI3L1 shows why the LOD line belongs on the plot. A share of 0.418 of the non-severe values lies below its LOD, against 0.073 of the severe values, so part of that difference is a protein in measurable amounts against a protein at background. KRT19 has 0.117 of its non-severe values below the LOD. For IL6, PTX3, TRIAP1 and LTBP2, no group has more than 0.010 below it, and the boxes move as a whole.
Hallmark gene sets
Section titled “Hallmark gene sets”A gene set test asks whether the members of a set sit together near the top or the bottom of a ranked list, here the Welch t-statistic of every gene on the panel. The 50 Hallmark sets of Liberzon et al. 2015 each summarize a well defined biological state. The image holds MSigDB v2026.1 as a GMT file exported at build time, so the run needs no network. Both tabs run the preranked GSEA of Subramanian et al. 2005 with a weight of 1, keep sets with at least 10 ranked genes, and fix the random seed.
The ranking needs one value per gene symbol. The Assay column holds the symbol, which is
what the GMT file uses, so the code joins on Assay rather than on UniProt, for which
the image holds no map to gene symbols. Seven kept assays join two genes in one name, such
as IL12A_IL12B, and the code drops them, because one measurement cannot stand for two
genes. CXCL8, IL6 and TNF have one assay on each of the four panels. The code keeps the
copy with the most samples above the LOD, and the lowest OlinkID on a tie, and drops the
other 8 copies.
The Hallmark memberships below come from MSigDB 2026.1.Hs, copyright Broad Institute, Massachusetts Institute of Technology, and Regents of the University of California, under CC BY 4.0. The MSigDB terms cover this collection. This lesson intersects the supplied memberships with the ranked panel genes and applies the stated minimum set size.
# One t-statistic per gene symbol. An Assay name such as IL12A_IL12B joins# two genes, so drop it. CXCL8, IL6 and TNF have one assay on each panel:# keep the copy with the most samples above LOD, then the lowest OlinkID.two_genes <- grepl("_", welch$Assay)gene_ranks <- welch[!two_genes, ] |> left_join(detection, by = "OlinkID") |> arrange(Assay, desc(above_lod), OlinkID) |> distinct(Assay, .keep_all = TRUE)ranks <- sort(setNames(gene_ranks$statistic, gene_ranks$Assay), decreasing = TRUE)cat("dropped:", sum(two_genes), "assays with two genes,", sum(!two_genes) - nrow(gene_ranks), "duplicate copies\n")gene_ranks |> filter(Assay %in% c("CXCL8", "IL6", "TNF")) |> transmute(Assay, OlinkID, above_lod = round(above_lod, 3)) |> as.data.frame() |> print(row.names = FALSE)
pathways <- gmtPathways("/opt/data/msigdb/h.all.v2026.1.Hs.symbols.gmt")coverage <- tibble( pathway = names(pathways), genes = lengths(pathways), on_panel = lengths(lapply(pathways, intersect, names(ranks))))cat("genes ranked:", length(ranks), " in any Hallmark set:", sum(names(ranks) %in% unlist(pathways)), "\n")cat("sets with 10 or more ranked genes:", sum(coverage$on_panel >= 10), "of", nrow(coverage), "\n")coverage |> mutate(share = round(on_panel / genes, 2)) |> arrange(desc(share)) |> slice(c(1:4, (n() - 3):n())) |> as.data.frame() |> print(row.names = FALSE)
set.seed(20261029)gsea <- fgsea(pathways, ranks, minSize = 10, maxSize = 500, BPPARAM = BiocParallel::SerialParam(progressbar = FALSE))gsea <- arrange(gsea, pval)cat("sets tested:", nrow(gsea), " FDR below 0.05:", sum(gsea$padj < 0.05), "\n")gsea |> head(10) |> transmute(pathway = sub("HALLMARK_", "", pathway), size, ES = round(ES, 3), NES = round(NES, 2), padj = signif(padj, 2)) |> as.data.frame() |> print(row.names = FALSE)dropped: 7 assays with two genes, 8 duplicate copies Assay OlinkID above_lod CXCL8 OID20631 1.000 IL6 OID20101 0.993 TNF OID20473 1.000genes ranked: 1138 in any Hallmark set: 570sets with 10 or more ranked genes: 34 of 50 pathway genes on_panel share HALLMARK_IL6_JAK_STAT3_SIGNALING 87 43 0.49 HALLMARK_ANGIOGENESIS 36 16 0.44 HALLMARK_EPITHELIAL_MESENCHYMAL_TRANSITION 200 79 0.40 HALLMARK_INFLAMMATORY_RESPONSE 200 65 0.32 HALLMARK_MITOTIC_SPINDLE 199 8 0.04 HALLMARK_SPERMATOGENESIS 135 5 0.04 HALLMARK_G2M_CHECKPOINT 200 6 0.03 HALLMARK_MYC_TARGETS_V1 200 6 0.03sets tested: 34 FDR below 0.05: 1 pathway size ES NES padj EPITHELIAL_MESENCHYMAL_TRANSITION 79 0.441 1.46 0.044 TNFA_SIGNALING_VIA_NFKB 44 0.464 1.46 0.130 IL6_JAK_STAT3_SIGNALING 43 0.463 1.45 0.130 INTERFERON_GAMMA_RESPONSE 42 0.444 1.39 0.230 COMPLEMENT 57 0.405 1.30 0.300 HYPOXIA 41 0.422 1.32 0.300 INFLAMMATORY_RESPONSE 65 0.386 1.26 0.300 IL2_STAT5_SIGNALING 45 0.405 1.28 0.300 ANGIOGENESIS 16 0.499 1.36 0.300 P53_PATHWAY 28 0.432 1.28 0.300def read_gmt(path): """Read a GMT file into a dict of gene set name to gene list.
Args: path: Path to a GMT file with the name, a description and the genes on each tab separated line.
Returns: dict: A map from the gene set name to its list of genes. """ gene_sets = {} with open(path) as handle: for line in handle: fields = line.rstrip("\n").split("\t") gene_sets[fields[0]] = fields[2:] return gene_sets
# One t-statistic per gene symbol. An Assay name such as IL12A_IL12B joins# two genes, so drop it. CXCL8, IL6 and TNF have one assay on each panel:# keep the copy with the most samples above LOD, then the lowest OlinkID.two_genes = welch["Assay"].str.contains("_")gene_ranks = welch[~two_genes].copy()gene_ranks["above_lod"] = ( above_lod.loc[gene_ranks["OlinkID"]].to_numpy(dtype=float))gene_ranks = gene_ranks.sort_values( ["Assay", "above_lod", "OlinkID"], ascending=[True, False, True]).drop_duplicates("Assay")ranks = (gene_ranks.set_index("Assay")["statistic"] .sort_values(ascending=False))print("dropped:", int(two_genes.sum()), "assays with two genes,", int((~two_genes).sum()) - len(gene_ranks), "duplicate copies")print(gene_ranks[gene_ranks["Assay"].isin(["CXCL8", "IL6", "TNF"])] [["Assay", "OlinkID", "above_lod"]] .to_string(index=False, formatters={"above_lod": "{:.3f}".format}))
pathways = read_gmt("/opt/data/msigdb/h.all.v2026.1.Hs.symbols.gmt")hallmark_genes = set().union(*pathways.values())on_panel = {name: len(set(genes) & set(ranks.index)) for name, genes in pathways.items()}print("genes ranked:", len(ranks), " in any Hallmark set:", int(ranks.index.isin(list(hallmark_genes)).sum()))print("sets with 10 or more ranked genes:", sum(count >= 10 for count in on_panel.values()), "of", len(pathways))
pre_res = gp.prerank( rnk=ranks, gene_sets=pathways, min_size=10, max_size=500, permutation_num=1000, weight=1.0, seed=20261029, threads=1, outdir=None, verbose=False,)gsea = pre_res.res2d.copy()for column in ["ES", "NES", "NOM p-val", "FDR q-val"]: gsea[column] = pd.to_numeric(gsea[column])gsea = gsea.sort_values(["NOM p-val", "FDR q-val"], kind="stable")print("sets tested:", len(gsea), " FDR below 0.05:", int((gsea["FDR q-val"] < 0.05).sum()))print(gsea.head(10).assign( Term=gsea["Term"].str.replace("HALLMARK_", ""), ES=gsea["ES"].round(3), NES=gsea["NES"].round(2),)[["Term", "ES", "NES", "NOM p-val", "FDR q-val"]].to_string(index=False))dropped: 7 assays with two genes, 8 duplicate copiesAssay OlinkID above_lodCXCL8 OID20631 1.000 IL6 OID20101 0.993 TNF OID20473 1.000genes ranked: 1138 in any Hallmark set: 570sets with 10 or more ranked genes: 34 of 50sets tested: 34 FDR below 0.05: 0 Term ES NES NOM p-val FDR q-valEPITHELIAL_MESENCHYMAL_TRANSITION 0.441 1.47 0.002000 0.342478 TNFA_SIGNALING_VIA_NFKB 0.464 1.46 0.005020 0.246065 IL6_JAK_STAT3_SIGNALING 0.463 1.47 0.011055 0.634787 INTERFERON_GAMMA_RESPONSE 0.444 1.40 0.024024 0.321745 HYPOXIA 0.422 1.33 0.051256 0.410393 COMPLEMENT 0.405 1.31 0.052000 0.324674 INFLAMMATORY_RESPONSE 0.386 1.26 0.071071 0.323536 ANGIOGENESIS 0.499 1.35 0.077003 0.419164 IL2_STAT5_SIGNALING 0.405 1.28 0.078078 0.301012 UNFOLDED_PROTEIN_RESPONSE 0.510 1.32 0.105092 0.389355Read the coverage table before the results. 1,138 genes are ranked and 570 of them belong to at least one Hallmark set. Coverage follows the panel design rather than the biology. 43 of the 87 genes of IL6_JAK_STAT3_SIGNALING are on the panel, against 6 of the 200 genes of MYC_TARGETS_V1 and of G2M_CHECKPOINT. Olink built the Explore panels around four themes, cardiometabolic, inflammation, neurology and oncology, so cytokines and their receptors are well covered and nuclear and cell cycle proteins are not. Only 34 of the 50 sets reach 10 ranked genes, and the rest are never tested.
That bias shapes the answer. Preranked GSEA compares each set with the rest of the list, and here the rest is the panel, not the genome, so an inflammation set must beat other inflammation proteins to pass. The cytokine sets share members, so their results overlap rather than add up. The test also permutes genes, not samples, which treats the proteins as independent, and cytokines that rise together look more coherent than that null expects.
The results are weak. fgsea finds one set at FDR 0.05, EPITHELIAL_MESENCHYMAL_TRANSITION with an adjusted p-value of 0.044. GSEApy finds none, with an FDR q-value of 0.342 for the same set, because it estimates the FDR in a different way. The four leading sets agree in both tools: EMT, TNF-alpha signaling via NF-kB, IL6 JAK STAT3 signaling and the interferon gamma response. Filbin et al. report enrichment of their severity proteins in IFN-gamma, IL-6 and TNF signaling, in KRAS signaling and in epithelial to mesenchymal transition, from Ingenuity Pathway Analysis against the measured protein set. The themes match. On a panel built around these pathways, a match of themes is the most a gene set test can show.
The ES is a deterministic running sum, and the two tools agree on it to a relative 2.4e-07. The NES divides the ES by the mean of 1,000 random sets that each tool draws on its own, so the two NES values differ by up to a relative 2.3e-02. The parity check allows 1e-5 for the ES and 0.05 for the NES.
metrics <- list( n_samples = nrow(samples), n_tested = nrow(welch), n_sig = sum(welch$Adjusted_pval < 0.05), n_sig_up = sum(welch$Adjusted_pval < 0.05 & welch$estimate > 0), fdr_cut = fdr_cut, heat_mean_z_severe = mean(z[, severe_cols]), pca_assays = ncol(pca_matrix), pca_var_pc1 = variance[1], pca_var_pc2 = variance[2], pc1_mean_severe = mean(scores$PC1[scores$Severity == "Severe"]), pc1_mean_non_severe = mean(scores$PC1[scores$Severity == "Non-severe"]), high_branch_severe = branch_table["high", "Severe"], high_branch_non_severe = branch_table["high", "Non-severe"], n_ranked = length(ranks), n_sets_tested = nrow(gsea))for (i in seq_len(nrow(box_summary))) { suffix <- paste0(box_summary$Assay[i], "_", sub("-", "_", tolower(box_summary$Severity[i]))) metrics[[paste0("median_", suffix)]] <- box_summary$median[i] metrics[[paste0("below_lod_", suffix)]] <- box_summary$below_lod[i]}for (i in seq_len(nrow(gsea))) { name <- tolower(sub("HALLMARK_", "", gsea$pathway[i])) metrics[[paste0("size_", name)]] <- gsea$size[i] metrics[[paste0("es_", name)]] <- gsea$ES[i] metrics[[paste0("nes_", name)]] <- gsea$NES[i]}write_json(metrics, "outputs/olink_visualization_metrics_r.json", auto_unbox = TRUE, digits = NA, pretty = TRUE)cat("wrote", length(metrics), "shared values\n")wrote 141 shared valuespc1 = scores["PC1"]metrics = { "n_samples": len(samples), "n_tested": len(welch), "n_sig": int((welch["fdr"] < 0.05).sum()), "n_sig_up": int(((welch["fdr"] < 0.05) & (welch["estimate"] > 0)).sum()), "fdr_cut": fdr_cut, "heat_mean_z_severe": z.loc[:, is_severe].to_numpy().mean(), "pca_assays": pca_matrix.shape[1], "pca_var_pc1": variance[0], "pca_var_pc2": variance[1], "pc1_mean_severe": pc1[is_severe].mean(), "pc1_mean_non_severe": pc1[~is_severe].mean(), "high_branch_severe": branch_table.loc["high", "Severe"], "high_branch_non_severe": branch_table.loc["high", "Non-severe"], "n_ranked": len(ranks), "n_sets_tested": len(gsea),}for assay, severity, median, below_lod in box_summary.itertuples( index=False): suffix = f"{assay}_{severity.lower().replace('-', '_')}" metrics[f"median_{suffix}"] = median metrics[f"below_lod_{suffix}"] = below_lod# Tag % reads leading edge genes / set size, so the size follows the slash.for term, es, nes, tag in zip(gsea["Term"], gsea["ES"], gsea["NES"], gsea["Tag %"]): name = term.replace("HALLMARK_", "").lower() metrics[f"size_{name}"] = int(tag.split("/")[1]) metrics[f"es_{name}"] = es metrics[f"nes_{name}"] = nesmetrics = {key: float(value) for key, value in metrics.items()}with open("outputs/olink_visualization_metrics_python.json", "w") as handle: json.dump(metrics, handle, indent=2)print("wrote", len(metrics), "shared values")
# The R tab ran first and wrote its own metrics file.with open("outputs/olink_visualization_metrics_r.json") as handle: metrics_r = json.load(handle)for prefix in ["es_", "nes_"]: gaps = [abs(value / metrics_r[key] - 1) for key, value in metrics.items() if key.startswith(prefix)] print(f"largest relative gap from R, {prefix[:-1]}: {max(gaps):.1e}")wrote 141 shared valueslargest relative gap from R, es: 2.4e-07largest relative gap from R, nes: 2.3e-02How this step fails
Section titled “How this step fails”- A volcano line at a raw p-value of 0.05 overstates what passes. Draw the line at the largest p-value that passes your FDR cut.
- A heatmap of the selected proteins always separates the groups. Treat it as a picture of the result, not as a test.
- A symbol join misses an assay whose name differs from the MSigDB symbol. List the panel symbols that match no set before you trust the coverage table.
msigdbr()downloads its gene sets on first use, so it fails in a container with no network. Read the exported GMT file in/opt/data/msigdb/instead.- On a targeted panel, a set with few members on the panel cannot be tested, and a set rich in panel proteins competes with its neighbors. Report the coverage with the result.
The code for this page is in the companion repository under
guides/proteomics/olink-visualization/.
Scientific references
Section titled “Scientific references”The OlinkAnalyze package by Nevola and colleagues supplies the functions for the analysis of Olink proteomic data.
Korotkevich and colleagues, 2016 describe the fast gene set enrichment analysis that fgsea implements.
Fang, Liu, and Peltz, 2022 describe GSEApy, the Python package for gene set enrichment analysis.
Further reading
Section titled “Further reading”Liberzon and colleagues, 2015, explain how the Hallmark collection reduces overlap among biological signatures. Subramanian and colleagues, 2005, describe the enrichment statistic and its null comparisons. Read both before interpreting a set whose measured members depend on the targeted panel.
The fgsea tutorial and GSEApy tutorial explain ranked inputs and gene-set files. Their parameter definitions help locate differences between the two implementations; neither source promises identical adjusted p-values.