Display paired features without inventing compound identities
A feature plot should show which plants supplied the effect estimate. A heatmap can expose a sample pattern, but its colors conceal the absolute scale and its rows can represent several ions from one compound. We retain feature identifiers, mass-to-charge values, retention times, and missing observations throughout the display.
These figures use the primary retained features and the same corrected, PQN-normalized values as the paired model. Feature selection follows adjusted p-value and then feature identifier. That selection serves a descriptive display; it does not create a second validation dataset.
Each displayed feature inherits the pipeline’s correspondence between injections. The differential result table preserves QC and biological exported retention-time spans alongside its effect estimates. Large spans require chromatogram review before interpretation, and a small p-value does not establish matching ions or a compound identity.
Preserve the plot pairs
Section titled “Preserve the plot pairs”The paired display selects the first three tested features. Every measured plant remains visible, and a line connects two plants only when both species have a measured value in that plot. An unpaired observation does not enter that feature’s paired effect estimate.
The printed observation count sums plant measurements across the selected features, so the same plant can contribute more than once.
These are the same BH findings discussed in the differential lesson. Their correspondence and normalization limits also apply to the displayed plant measurements.
The heatmap selects up to twenty tested features and subtracts each row’s observed mean log2 area. Gray cells represent absent measurements. No zero replacement or imputation supplies a color, and the fixed column order places the two species from each plot together.
The source data are Dietz and colleagues’ MTBLS865 deposit, released publicly by MetaboLights in 2020 under EMBL-EBI Terms of Use. The repository’s public data policy permits reuse, and its data guide permits modification. The source notice identifies the authors, original files, and this analysis’s selection and transformations.
library(ggplot2)library(jsonlite)library(patchwork)source("/shared/statistics.R")options(digits = 17)
data <- LoadFeatureData()quality <- SummarizeQuality(data)drift <- CorrectDrift(data)primary <- NormalizeBiological(data, drift$corrected, quality$main_retained, method = "pqn")result <- PairedResults(data$features, primary$metadata, primary$matrix, quality$main_retained)selected <- result[result$tested, ]selected <- head(selected[order(selected$adjusted_p_value, selected$feature_id), ], 20)stopifnot(nrow(selected) >= 3L)rows <- match(selected$feature_id, data$features$feature_id)pairs <- PairColumns(primary$metadata)columns <- as.vector(rbind(pairs$dactylis, pairs$galium))ordered_metadata <- primary$metadata[columns, ]row_matrix <- primary$matrix[rows, columns, drop = FALSE]centered <- sweep(row_matrix, 1, rowMeans(row_matrix, na.rm = TRUE), "-")heatmap_data <- data.frame( feature_id = rep(selected$feature_id, each = length(columns)), injection_id = rep(ordered_metadata$injection_id, nrow(selected)), centered_log2 = as.vector(t(centered)))write.csv(heatmap_data, "outputs/heatmap_data_r.csv", row.names = FALSE, na = "NA")plot_data <- list()for (index in seq_len(3L)) { row <- rows[index] table <- ordered_metadata[, c("injection_id", "plot", "species")] table$feature_id <- data$features$feature_id[row] table$mz <- data$features$mz[row] table$retention_time_seconds <- data$features$retention_time_seconds[row] table$log2_area <- primary$matrix[row, columns] complete <- is.finite(primary$matrix[row, pairs$dactylis]) & is.finite(primary$matrix[row, pairs$galium]) table$complete_pair <- table$plot %in% pairs$plots[complete] plot_data[[index]] <- table}plot_data <- do.call(rbind, plot_data)rownames(plot_data) <- NULLwrite.csv(plot_data, "outputs/paired_display_r.csv", row.names = FALSE, na = "NA")metrics <- list( displayed_features = nrow(selected), paired_features = 3L, heatmap_missing_cells = sum(!is.finite(centered)), paired_display_observations = sum(is.finite(plot_data$log2_area)))write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE)cat("Heatmap features:", metrics$displayed_features, "\n")cat("Missing heatmap measurements:", metrics$heatmap_missing_cells, "\n")cat("Measured plants in the paired display:", metrics$paired_display_observations, "\n")Heatmap features: 20Missing heatmap measurements: 14Measured plants in the paired display: 34heatmap_data$feature_id <- factor(heatmap_data$feature_id, levels = rev(selected$feature_id))heatmap_data$injection_id <- factor(heatmap_data$injection_id, levels = ordered_metadata$injection_id)labels <- paste(ordered_metadata$plot, ifelse(ordered_metadata$species == "Galium mollugo", "G", "D"))heatmap <- ggplot(heatmap_data, aes(injection_id, feature_id, fill = centered_log2)) + geom_tile() + scale_fill_gradient2(low = "#286b86", mid = "white", high = "#b85c38", midpoint = 0, na.value = "gray70") + scale_x_discrete(labels = labels) + labs(x = "Plot and species", y = "Feature", fill = "Centered\nlog2 area", title = "Selected features after primary normalization") + theme_minimal(base_size = 10) + theme(axis.text.x = element_text(angle = 55, hjust = 1))ggsave("outputs/feature_heatmap_r.png", heatmap, width = 10, height = 7, dpi = 160, bg = "white")plot_data$species <- factor(plot_data$species, c("Dactylis glomerata", "Galium mollugo"))plot_data$feature_label <- sprintf("%s | m/z %.4f | RT %.1f s", plot_data$feature_id, plot_data$mz, plot_data$retention_time_seconds)paired <- ggplot(plot_data, aes(species, log2_area, group = plot, color = plot)) + geom_line(data = plot_data[plot_data$complete_pair, ], alpha = 0.6) + geom_point(size = 2, na.rm = TRUE) + facet_wrap(~feature_label, scales = "free_y", nrow = 1) + scale_x_discrete(labels = c("Dactylis", "Galium")) + labs(x = "Species", y = "Corrected and PQN-normalized log2 area", color = "Plot", title = "Each line identifies one complete plot pair") + theme_minimal(base_size = 10) + theme(legend.position = "bottom")ggsave("outputs/paired_features_r.png", paired, width = 12, height = 4.5, dpi = 160, bg = "white")

import importlib.utilimport jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
spec = importlib.util.spec_from_file_location("metabo", "/shared/statistics.py")metabo = importlib.util.module_from_spec(spec)spec.loader.exec_module(metabo)data = metabo.load_feature_data()quality = metabo.summarize_quality(data)corrected, drift = metabo.correct_drift(data)matrix, factors, metadata = metabo.normalize_biological( data, corrected, quality["main_retained"].to_numpy(), method="pqn")result = metabo.paired_results(data["features"], metadata, matrix, quality["main_retained"].to_numpy())selected = result.loc[result["tested"]].sort_values( ["adjusted_p_value", "feature_id"]).head(20)assert len(selected) >= 3rows = data["features"].set_index("feature_id").index.get_indexer( selected["feature_id"])plots, dactylis, galium = metabo.pair_columns(metadata)columns = np.column_stack([dactylis, galium]).ravel()ordered_metadata = metadata.iloc[columns].reset_index(drop=True)row_matrix = matrix[np.ix_(rows, columns)]centered = row_matrix - np.nanmean(row_matrix, axis=1)[:, None]heatmap_data = pd.DataFrame({ "feature_id": np.repeat(selected["feature_id"].to_numpy(), len(columns)), "injection_id": np.tile(ordered_metadata["injection_id"], len(selected)), "centered_log2": centered.ravel(),})plot_tables = []for row in rows[:3]: table = ordered_metadata[["injection_id", "plot", "species"]].copy() for name in ["feature_id", "mz", "retention_time_seconds"]: table[name] = data["features"].loc[row, name] table["log2_area"] = matrix[row, columns] complete = (np.isfinite(matrix[row, dactylis]) & np.isfinite(matrix[row, galium])) table["complete_pair"] = table["plot"].isin(np.asarray(plots)[complete]) plot_tables.append(table)plot_data = pd.concat(plot_tables, ignore_index=True)for name, frame in [("heatmap_data", heatmap_data), ("paired_display", plot_data)]: frame.to_csv(f"outputs/{name}_python.csv", index=False, na_rep="NA") expected = pd.read_csv(f"outputs/{name}_r.csv", dtype={"feature_id": str}) pd.testing.assert_frame_equal(frame, expected, check_dtype=False, check_names=False, rtol=1e-9, atol=1e-10)metrics = { "displayed_features": len(selected), "paired_features": 3, "heatmap_missing_cells": int((~np.isfinite(centered)).sum()), "paired_display_observations": int(plot_data["log2_area"].notna().sum()),}Path("outputs/metrics_python.json").write_text(json.dumps(metrics, indent=2))print("Heatmap features:", metrics["displayed_features"])print("Missing heatmap measurements:", metrics["heatmap_missing_cells"])print("Measured plants in the paired display:", metrics["paired_display_observations"])Heatmap features: 20Missing heatmap measurements: 14Measured plants in the paired display: 34figure, axis = plt.subplots(figsize=(10, 7))color_map = plt.get_cmap("RdBu_r").copy()color_map.set_bad("0.7")limit = np.nanmax(np.abs(centered))image = axis.imshow(np.ma.masked_invalid(centered), aspect="auto", cmap=color_map, vmin=-limit, vmax=limit)labels = [f"{plot} {'G' if species == 'Galium mollugo' else 'D'}" for plot, species in zip(ordered_metadata["plot"], ordered_metadata["species"], strict=True)]axis.set_xticks(np.arange(len(columns)), labels, rotation=55, ha="right")axis.set_yticks(np.arange(len(selected)), selected["feature_id"])axis.set_xlabel("Plot and species")axis.set_ylabel("Feature")axis.set_title("Selected features after primary normalization")figure.colorbar(image, ax=axis, label="Centered log2 area")figure.tight_layout()figure.savefig("outputs/feature_heatmap_python.png", dpi=160, facecolor="white")plt.close(figure)figure, axes = plt.subplots(1, 3, figsize=(12, 4.8))colors = plt.get_cmap("tab10")(np.arange(len(plots)))for axis, row in zip(axes, rows[:3], strict=True): feature = data["features"].iloc[row] for number, plot in enumerate(plots): y = matrix[row, [dactylis[number], galium[number]]] observed = np.isfinite(y) if observed.all(): axis.plot([0, 1], y, color=colors[number], alpha=0.6) axis.scatter(np.array([0, 1])[observed], y[observed], color=colors[number], label=plot, s=25) axis.set_xticks([0, 1], ["Dactylis", "Galium"]) axis.set_xlabel("Species") axis.set_ylabel("Corrected and PQN-normalized log2 area") axis.set_title(f"{feature['feature_id']}\nm/z {feature['mz']:.4f}, " f"RT {feature['retention_time_seconds']:.1f} s", fontsize=10)handles, labels = axes[-1].get_legend_handles_labels()figure.legend(handles, labels, loc="lower center", ncol=6, title="Plot", frameon=False, fontsize=8)figure.tight_layout(rect=(0, 0.14, 1, 1))figure.savefig("outputs/paired_features_python.png", dpi=160, facecolor="white")plt.close(figure)

Stop at the available identity evidence
Section titled “Stop at the available identity evidence”This assay provides MS1 measurements. Accurate mass can generate candidate formulas or adduct hypotheses, but coelution, isobars, fragments, and multiple adducts prevent a direct feature-to-compound assignment. A standard measured in the same acquisition supports the standard check described in identification confidence; it does not identify an unrelated biological feature by proximity alone.
Pathway inference requires supported compound identities, a resource appropriate for these plant species, and a detected background defined by the analytical assay. Multiple ions from one compound need an explicit aggregation rule before enrichment. Without those inputs, a ranked pathway list converts uncertain annotations into unsupported biological claims. This example therefore reports measured feature patterns and preserves the evidence still required for a compound-level analysis.
Further reading
Section titled “Further reading”-
MSI reporting of unknown metabolites
The paper permits reports of unknown signals with their measured spectral and chromatographic properties. Its identity requirements explain why an ion-feature label cannot supply a compound name.
-
The authors explain normalization through a reference quotient distribution. Read that assumption alongside the corrected values and normalization sensitivity shown in this section.