Show effects and their supporting cultures
A volcano plot summarizes thousands of tests but hides the observations behind each point. A protein group supported by six cultures and a group supported by four can occupy similar positions. The supporting measurements belong beside the summary.
This lesson uses the accepted differential results and the same canonical abundance matrix. It does not fit a different model for the figure.
Make the contrast readable
Section titled “Make the contrast readable”The volcano plot places the resistant-versus-parental log2 coefficient on the horizontal axis. Its vertical axis states whether it uses the raw or adjusted p-value. The decision rule remains explicit, and values outside the displayed range retain their uncapped values in the output table.
Labels follow a declared selection rule. They identify the protein group and preserve ambiguous membership in the companion table. A convenient representative accession does not justify a gene-specific biological claim.
Groups without a continuous abundance test do not receive invented volcano coordinates. Their one-condition detection patterns remain in the descriptive output from the missing-value lesson.
Put biological observations on the page
Section titled “Put biological observations on the page”Culture-level plots show every observed log2 abundance for selected groups. Missing cultures remain visible as missing measurements rather than disappearing from the denominator. The condition summaries use the same sample assignments as the model.
A group with one unusual culture deserves inspection even when its moderated p-value is small. The figure lets a reader compare the estimated condition difference with the observed variability and peptide support.
Explain what a heatmap changes
Section titled “Explain what a heatmap changes”The heatmap selects up to 20 tested groups by increasing moderated BH value, then decreasing absolute effect, then group identifier. It retains the canonical sample order. Each row subtracts its observed mean and divides by its observed sample standard deviation. Row scaling makes patterns comparable within rows while removing direct intensity comparisons between different proteins.
Missing entries use a separate color. They are not assigned the lowest observed intensity. A clustered heatmap can suggest structure, but the tree does not add independent evidence to a condition test that used the same measurements.
The companion writes the plotted data with every figure. That output preserves sample order, selected groups, displayed values, and label choices, so the image remains connected to its underlying observations.
Draw the model and the measurements together
Section titled “Draw the model and the measurements together”The culture and interval figures use the first six groups under the same selection rule. Selection uses these results, so the figures explain the fitted comparison rather than validate it independently. The interval bars use the primary limma posterior variance and moderated degrees of freedom.
The volcano uses moderated BH values. It places underflowed zero values at the smallest positive floating-point value for display and retains the original values in the table. The culture figure marks each absent measurement with NA below the observed range; that display position is not an imputed intensity.
Interpret this cohort
Section titled “Interpret this cohort”The selected culture plots contain 36 observed values across 6 groups. The heatmap displays 20 groups under the stated selection rule.
Each label identifies a protein group in the companion table. Read its complete membership before attaching a gene-specific biological explanation.
library(ggplot2)library(jsonlite)source("/shared/ms_common.R")source("/shared/ms_models.R")data <- PrepareMsAnalysis(LoadMsData())primary <- FitMsLimma(data)WriteMsModelProvenance("outputs/model_provenance_r.json")primary$members <- data$groups$memberswrite.csv(primary, "outputs/primary_limma_r.csv", row.names = FALSE, na = "NA")ordinary <- FitMsOrdinary(data)write.csv(ordinary, "outputs/ordinary_r.csv", row.names = FALSE, na = "NA")ranked <- primary[primary$tested, ]ranked <- ranked[order(ranked$adjusted_p_value, -abs(ranked$log2_fold_change), ranked$group_id), ]selected <- head(ranked, 6L)selected_index <- match(selected$group_id, data$groups$group_id)cultures <- data.frame( group_id = rep(selected$group_id, each = 6L), sample_id = rep(data$samples$sample_id, nrow(selected)), condition = rep(data$samples$condition, nrow(selected)), log2_abundance = as.vector(t(data$normalized[selected_index, , drop = FALSE])))write.csv(cultures, "outputs/culture_points_r.csv", row.names = FALSE, na = "NA")write.csv(selected, "outputs/selected_intervals_r.csv", row.names = FALSE, na = "NA")heatmap_ids <- head(ranked$group_id, 20L)heatmap_values <- data$normalized[ match(heatmap_ids, data$groups$group_id), , drop = FALSE]center <- rowMeans(heatmap_values, na.rm = TRUE)spread <- apply(heatmap_values, 1, sd, na.rm = TRUE)stopifnot(all(is.finite(spread)), all(spread > 0))heatmap_values <- sweep(sweep(heatmap_values, 1, center, "-"), 1, spread, "/")heatmap_table <- data.frame(group_id = heatmap_ids, heatmap_values, check.names = FALSE)write.csv(heatmap_table, "outputs/heatmap_values_r.csv", row.names = FALSE, na = "NA")metrics <- list(tested_groups = nrow(ranked), selected_groups = nrow(selected), observed_points = sum(!is.na(cultures$log2_abundance)), missing_points = sum(is.na(cultures$log2_abundance)), heatmap_groups = length(heatmap_ids))write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE)cat("Tested groups on the volcano:", metrics$tested_groups, "\n")cat("Groups with culture and interval plots:", metrics$selected_groups, "\n")cat("Observed culture points:", metrics$observed_points, "\n")cat("Explicitly absent culture points:", metrics$missing_points, "\n")Tested groups on the volcano: 463Groups with culture and interval plots: 6Observed culture points: 36Explicitly absent culture points: 0ranked$display_score <- -log10(pmax(ranked$adjusted_p_value, .Machine$double.xmin))ranked$discovery <- ranked$adjusted_p_value < 0.05volcano <- ggplot(ranked, aes(log2_fold_change, display_score, color = discovery)) + geom_point(alpha = 0.5, size = 0.9) + geom_hline(yintercept = -log10(0.05), linetype = "dashed") + scale_color_manual(values = c("FALSE" = "#87969c", "TRUE" = "#bf5b3d")) + labs(x = "Resistant minus parental log2 effect", y = "-log10 moderated BH value", color = "BH < 0.05") + theme_minimal(base_size = 11)ggsave("outputs/volcano_r.png", volcano, width = 7, height = 5, dpi = 160, bg = "white")missing_floor <- min(cultures$log2_abundance, na.rm = TRUE) - 1cultures$display_value <- ifelse(is.na(cultures$log2_abundance), missing_floor, cultures$log2_abundance)cultures$sample_id <- factor(cultures$sample_id, levels = data$samples$sample_id)points <- ggplot(cultures, aes(sample_id, display_value, color = condition)) + geom_point(data = cultures[!is.na(cultures$log2_abundance), ], size = 2) + geom_text(data = cultures[is.na(cultures$log2_abundance), ], label = "NA", size = 3, show.legend = FALSE) + facet_wrap(~group_id, ncol = 2) + scale_x_discrete(drop = FALSE) + scale_color_manual(values = c(parental = "#2c7c90", resistant = "#b65c3a")) + labs(x = "Culture", y = "Normalized log2 abundance", color = "Condition") + theme_minimal(base_size = 10) + theme(axis.text.x = element_text(angle = 45, hjust = 1))ggsave("outputs/culture_points_r.png", points, width = 11, height = 9, dpi = 160, bg = "white")selected$group_id <- factor(selected$group_id, levels = rev(selected$group_id))intervals <- ggplot(selected, aes(log2_fold_change, group_id)) + geom_vline(xintercept = 0, color = "gray65") + geom_segment(aes(x = ci_lower, xend = ci_upper, yend = group_id)) + geom_point(size = 2, color = "#287c8e") + labs(x = "Resistant minus parental log2 effect with 95% interval", y = "Protein group") + theme_minimal(base_size = 10)ggsave("outputs/effect_intervals_r.png", intervals, width = 9, height = 5, dpi = 160, bg = "white")heatmap_long <- data.frame( group_id = factor(rep(heatmap_ids, each = 6L), levels = rev(heatmap_ids)), sample_id = factor(rep(data$samples$sample_id, length(heatmap_ids)), levels = data$samples$sample_id), row_z_score = as.vector(t(heatmap_values)))heatmap_plot <- ggplot( heatmap_long, aes(sample_id, group_id, fill = row_z_score)) + geom_tile(color = "white") + scale_fill_gradient2(low = "#3475a3", mid = "white", high = "#b5423d", na.value = "#d9d9d9") + labs(x = "Culture", y = "Protein group", fill = "Observed row z-score") + theme_minimal(base_size = 9) + theme(axis.text.x = element_text(angle = 45, hjust = 1))ggsave("outputs/group_heatmap_r.png", heatmap_plot, width = 9, height = 8, dpi = 160, bg = "white")



import importlib.utilimport jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
modules = {}for name in ["ms_common", "ms_models"]: spec = importlib.util.spec_from_file_location(name, f"/shared/{name}.py") module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) modules[name] = modulems, models = modules["ms_common"], modules["ms_models"]data = ms.prepare_ms_analysis(ms.load_ms_data())ordinary = models.fit_ordinary(data)pd.testing.assert_frame_equal( ordinary, pd.read_csv("outputs/ordinary_r.csv"), check_dtype=False, rtol=1e-10, atol=1e-10)primary = pd.read_csv("outputs/primary_limma_r.csv")if not primary["group_id"].equals(ordinary["group_id"]): raise ValueError("The model and canonical group orders differ")np.testing.assert_array_equal(primary["tested"], ordinary["tested"])np.testing.assert_allclose(primary["log2_fold_change"], ordinary["log2_fold_change"], equal_nan=True, rtol=1e-10, atol=1e-10)ranked = primary.loc[primary["tested"]].copy()ranked["absolute_effect"] = ranked["log2_fold_change"].abs()ranked = ranked.sort_values(["adjusted_p_value", "absolute_effect", "group_id"], ascending=[True, False, True], kind="stable")selected = ranked.head(6)indices = data["groups"]["group_id"].tolist()selected_index = [indices.index(value) for value in selected["group_id"]]cultures = pd.DataFrame({ "group_id": np.repeat(selected["group_id"].to_numpy(), 6), "sample_id": np.tile(data["samples"]["sample_id"], len(selected)), "condition": np.tile(data["samples"]["condition"], len(selected)), "log2_abundance": data["normalized"][selected_index].ravel(),})pd.testing.assert_frame_equal( cultures, pd.read_csv("outputs/culture_points_r.csv"), check_dtype=False, rtol=1e-10, atol=1e-10)cultures.to_csv("outputs/culture_points_python.csv", index=False, na_rep="NA")heatmap_ids = ranked["group_id"].head(20).tolist()values = data["normalized"][[indices.index(value) for value in heatmap_ids]]center = np.nanmean(values, axis=1, keepdims=True)spread = np.nanstd(values, axis=1, ddof=1, keepdims=True)if not np.isfinite(spread).all() or np.any(spread <= 0): raise ValueError("A selected heatmap group has no finite variation")heatmap_values = (values - center) / spreadheatmap_table = pd.DataFrame(heatmap_values, columns=data["samples"]["sample_id"])heatmap_table.insert(0, "group_id", heatmap_ids)pd.testing.assert_frame_equal( heatmap_table, pd.read_csv("outputs/heatmap_values_r.csv"), check_dtype=False, check_names=False, rtol=1e-10, atol=1e-10)heatmap_table.to_csv("outputs/heatmap_values_python.csv", index=False, na_rep="NA")metrics = { "tested_groups": len(ranked), "selected_groups": len(selected), "observed_points": int(cultures["log2_abundance"].notna().sum()), "missing_points": int(cultures["log2_abundance"].isna().sum()), "heatmap_groups": len(heatmap_ids),}Path("outputs/metrics_python.json").write_text(json.dumps(metrics, indent=2))print("Tested groups on the volcano:", metrics["tested_groups"])print("Groups with culture and interval plots:", metrics["selected_groups"])print("Observed culture points:", metrics["observed_points"])print("Explicitly absent culture points:", metrics["missing_points"])Tested groups on the volcano: 463Groups with culture and interval plots: 6Observed culture points: 36Explicitly absent culture points: 0score = -np.log10(np.maximum(ranked["adjusted_p_value"], np.finfo(float).tiny))colors = np.where(ranked["adjusted_p_value"] < 0.05, "#bf5b3d", "#87969c")figure, axis = plt.subplots(figsize=(7, 5))axis.scatter(ranked["log2_fold_change"], score, c=colors, s=5, alpha=0.5)axis.axhline(-np.log10(0.05), linestyle="--", color="gray")axis.set_xlabel("Resistant minus parental log2 effect")axis.set_ylabel("-log10 moderated BH value")figure.tight_layout()figure.savefig("outputs/volcano_python.png", dpi=160, facecolor="white")plt.close(figure)missing_floor = cultures["log2_abundance"].min() - 1figure, axes = plt.subplots(3, 2, figsize=(11, 9), sharey=True)for axis, group_id in zip(axes.flat, selected["group_id"]): table = cultures.loc[cultures["group_id"].eq(group_id)] for position, row in enumerate(table.itertuples(index=False)): color = "#2c7c90" if row.condition == "parental" else "#b65c3a" if np.isfinite(row.log2_abundance): axis.scatter(position, row.log2_abundance, color=color, s=22) else: axis.text(position, missing_floor, "NA", color=color, ha="center") axis.set_xticks(range(6), data["samples"]["sample_id"], rotation=45, ha="right", fontsize=8) axis.set_title(group_id, fontsize=9) axis.set_ylabel("Normalized log2 abundance")for axis in axes.flat[len(selected):]: axis.set_visible(False)figure.tight_layout()figure.savefig("outputs/culture_points_python.png", dpi=160, facecolor="white")plt.close(figure)figure, axis = plt.subplots(figsize=(9, 5))positions = np.arange(len(selected))axis.hlines(positions, selected["ci_lower"], selected["ci_upper"], color="gray")axis.scatter(selected["log2_fold_change"], positions, s=20, color="#287c8e")axis.axvline(0, color="gray", linewidth=0.8)axis.set_yticks(positions, selected["group_id"], fontsize=9)axis.invert_yaxis()axis.set_xlabel("Resistant minus parental log2 effect with 95% interval")figure.tight_layout()figure.savefig("outputs/effect_intervals_python.png", dpi=160, facecolor="white")plt.close(figure)figure, axis = plt.subplots(figsize=(9, 8))palette = plt.get_cmap("coolwarm").copy()palette.set_bad("#d9d9d9")limit = np.nanmax(np.abs(heatmap_values))image = axis.imshow(heatmap_values, aspect="auto", cmap=palette, vmin=-limit, vmax=limit)axis.set_xticks(range(6), data["samples"]["sample_id"], rotation=45, ha="right")axis.set_yticks(range(len(heatmap_ids)), heatmap_ids, fontsize=8)figure.colorbar(image, ax=axis, label="Observed row z-score")figure.tight_layout()figure.savefig("outputs/group_heatmap_python.png", dpi=160, facecolor="white")plt.close(figure)



Python recomputes the observed-value transformations and verifies them against R. Both figures use the same fresh R limma results for moderated p-values and intervals. The gray heatmap cells and NA culture labels retain the difference between an absent measurement and a low measured abundance.
Further reading
Section titled “Further reading”The R linear model reference explains how a design formula and its contrasts determine fitted coefficients. Use those definitions when assigning the direction of the resistant-versus-parental axis.
The R p-value adjustment reference defines the BH adjustment used for the displayed decisions. It helps distinguish a plot of raw p-values from the adjusted values used to select protein groups.