Two-Group Comparison
A two-group figure should show the observations and the size of the comparison. Choose the experimental unit and target quantity before choosing the test. A Shapiro-Wilk or Levene p-value does not automatically select the appropriate analysis.
This page uses two invented datasets with independent samples. Tumor volume illustrates a treated-minus-control arithmetic mean difference. IL-6 illustrates a treated-to-control geometric mean ratio, estimated by comparing natural logarithms and exponentiating the estimate and interval. The log scale follows that stated multiplicative question; it is not a response to a normality test.
Both examples use Welch’s method on their stated analysis scale. It allows unequal group variances. Small samples, influential observations, and model assumptions still need attention. A paired experiment requires a paired analysis, and repeated measurements require an analysis that accounts for dependence.
Get the data
Section titled “Get the data”Download tumor_volume.csv and cytokine_pg_ml.csv. Save them in a folder named fixtures beside the folder where you run this page’s code. Each table contains twelve control and twelve treated observations. These invented values demonstrate the figure; they provide no evidence about a treatment.
The examples use R with ggplot2 and jsonlite, or Python with pandas, NumPy, SciPy, Matplotlib, and seaborn. Run the blocks for one language in order. The companion directory requires repository access. Its runner uses the locked proteomics:0.1.1 image with the fixture folder mounted at /fixtures and network access disabled.
Draw the estimate with the observations
Section titled “Draw the estimate with the observations”The function below receives the analysis scale explicitly. It never chooses a test from a diagnostic p-value. Both languages put the treated group first in the calculation, so the signs and ratio direction agree. The plot shows every observation once and labels the numerical p-value, effect estimate, and 95% interval.
library(ggplot2)
fixture_directory <- if (dir.exists("/fixtures")) "/fixtures" else "../fixtures"dir.create("outputs", showWarnings = FALSE)
#' Draw a two-group comparison with a prespecified analysis scale.#'#' @param csv_path Path to the fixture with group and response columns.#' @param response Name of the response column.#' @param axis_label Label with measurement units.#' @param output_path Path to the PNG figure.#' @param log_scale Whether to compare natural logarithms and report a ratio.#' @return A named numeric vector with the estimate, interval, and p-value.MakeComparison <- function(csv_path, response, axis_label, output_path, log_scale = FALSE) { data <- read.csv(csv_path) data$group <- factor(data$group, levels = c("control", "treated")) values <- data[[response]] stopifnot(all(is.finite(values)), !anyNA(data$group)) if (log_scale) { stopifnot(all(values > 0)) values <- log(values) } treated <- values[data$group == "treated"] control <- values[data$group == "control"] comparison <- t.test(treated, control, var.equal = FALSE) estimate <- mean(treated) - mean(control) interval <- comparison$conf.int label <- "Mean difference, treated - control" if (log_scale) { estimate <- exp(estimate) interval <- exp(interval) label <- "Geometric mean ratio, treated / control" } subtitle <- sprintf("%s\n%.3f, 95%% CI [%.3f, %.3f]; p = %.3g", label, estimate, interval[1], interval[2], comparison$p.value) plot <- ggplot(data, aes(group, .data[[response]], fill = group)) + geom_boxplot(width = 0.6, outlier.shape = NA, alpha = 0.4) + geom_point(position = position_jitter(width = 0.12, seed = 42), size = 2, shape = 21) + scale_fill_manual(values = c("#3B6DB3", "#C1432B")) + labs(x = "Group", y = axis_label, subtitle = subtitle) + theme_classic(base_size = 11) + theme(legend.position = "none") if (log_scale) { plot <- plot + scale_y_log10() } ggsave(output_path, plot, width = 5.2, height = 4.4, dpi = 180) cat(sprintf("%s: estimate = %.4f, 95%% CI [%.4f, %.4f], p = %.6g\n", response, estimate, interval[1], interval[2], comparison$p.value)) c(estimate = estimate, lower = interval[1], upper = interval[2], p_value = comparison$p.value)}tumor_result <- MakeComparison( file.path(fixture_directory, "tumor_volume.csv"), "volume", "Tumor volume (mm^3)", "outputs/two_group_tumor_r.png")volume: estimate = -41.9167, 95% CI [-50.5860, -33.2474], p = 1.87789e-09
il6_result <- MakeComparison( file.path(fixture_directory, "cytokine_pg_ml.csv"), "concentration", "IL-6 (pg/mL), logarithmic axis", "outputs/two_group_il6_r.png", log_scale = TRUE)metrics <- c(setNames(tumor_result, paste0("tumor_", names(tumor_result))), setNames(il6_result, paste0("il6_", names(il6_result))))jsonlite::write_json(as.list(metrics), "outputs/metrics_r.json", auto_unbox = TRUE, digits = NA)concentration: estimate = 2.4799, 95% CI [1.8337, 3.3538], p = 3.14472e-06
import jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport seaborn as snsfrom scipy import stats
fixture_directory = Path("/fixtures")if not fixture_directory.is_dir(): fixture_directory = Path("../fixtures")Path("outputs").mkdir(exist_ok=True)
def make_comparison(csv_path, response, axis_label, output_path, log_scale=False): """Draw a comparison using a prespecified analysis scale.
Args: csv_path: Path to the fixture with group and response columns. response: Name of the response column. axis_label: Label with measurement units. output_path: Path to the PNG figure. log_scale: Whether to compare logarithms and report a ratio.
Returns: A dictionary with the estimate, interval, and p-value.
Raises: ValueError: If values are nonfinite or invalid for the log scale. """ data = pd.read_csv(csv_path) values = data[response].to_numpy() if not np.isfinite(values).all(): raise ValueError("Responses must be finite.") if log_scale: if np.any(values <= 0): raise ValueError("Log-scale responses must be positive.") values = np.log(values) treated = values[data["group"] == "treated"] control = values[data["group"] == "control"] comparison = stats.ttest_ind(treated, control, equal_var=False) estimate = treated.mean() - control.mean() interval = comparison.confidence_interval(confidence_level=0.95) lower, upper = interval.low, interval.high label = "Mean difference, treated - control" if log_scale: estimate, lower, upper = np.exp([estimate, lower, upper]) label = "Geometric mean ratio, treated / control" title = (f"{label}\n{estimate:.3f}, 95% CI [{lower:.3f}, {upper:.3f}]; " f"p = {comparison.pvalue:.3g}") figure, axis = plt.subplots(figsize=(5.2, 4.4)) order = ["control", "treated"] colors = ["#3B6DB3", "#C1432B"] sns.boxplot(data=data, x="group", y=response, hue="group", order=order, palette=colors, legend=False, width=0.6, fliersize=0, ax=axis) rng = np.random.default_rng(42) for position, group_name in enumerate(order): observed = data.loc[data["group"] == group_name, response] jitter = rng.uniform(-0.12, 0.12, size=len(observed)) axis.scatter(position + jitter, observed, s=24, color=colors[position], edgecolor="black", linewidth=0.4, zorder=3) if log_scale: axis.set_yscale("log") axis.set(xlabel="Group", ylabel=axis_label, title=title) sns.despine(ax=axis) figure.tight_layout() figure.savefig(output_path, dpi=180) plt.close(figure) print(f"{response}: estimate = {estimate:.4f}, " f"95% CI [{lower:.4f}, {upper:.4f}], p = {comparison.pvalue:.6g}") return {"estimate": float(estimate), "lower": float(lower), "upper": float(upper), "p_value": float(comparison.pvalue)}tumor_result = make_comparison( fixture_directory / "tumor_volume.csv", "volume", "Tumor volume (mm^3)", "outputs/two_group_tumor_python.png")volume: estimate = -41.9167, 95% CI [-50.5860, -33.2474], p = 1.87789e-09
il6_result = make_comparison( fixture_directory / "cytokine_pg_ml.csv", "concentration", "IL-6 (pg/mL), logarithmic axis", "outputs/two_group_il6_python.png", log_scale=True)metrics = {}for prefix, result in (("tumor", tumor_result), ("il6", il6_result)): for name, value in result.items(): metrics[f"{prefix}_{name}"] = valuePath("outputs/metrics_python.json").write_text(json.dumps(metrics, indent=2))concentration: estimate = 2.4799, 95% CI [1.8337, 3.3538], p = 3.14472e-06
Read the comparison
Section titled “Read the comparison”A negative tumor-volume difference means a lower treated arithmetic mean. The no-difference value is zero. An IL-6 ratio above one means a higher treated geometric mean, and its no-difference value is one. The ratio is not a difference between arithmetic means or a comparison of medians.
The intervals quantify uncertainty under the stated models. The p-values test a zero difference on the analysis scale. Both languages calculate the same estimates and intervals; the runner checks their numerical agreement. The figures can differ in their boxplot conventions and point positions without changing the estimates.
The two datasets illustrate separate analysis questions. If an actual study selects results across several outcomes, define that hypothesis family and use an appropriate multiple-testing procedure.
Make the figure interpretable
Section titled “Make the figure interpretable”- Show the individual observations and state the number of independent samples. Technical replicates do not increase that sample count.
- State the comparison direction, analysis scale, and units. A reader must distinguish a mean difference from a ratio.
- Show the effect estimate and its interval with the numerical p-value. A significance star does not report the magnitude or precision of an effect.
- Explain a transformation before interpreting its output. Values at or below zero cannot enter this log-scale example.
Check your understanding
Section titled “Check your understanding”The same twelve subjects contribute measurements before and after treatment. Can this function analyze those measurements as two independent groups?
It cannot. Preserve the subject pairs and analyze within-subject differences, or use a model that represents the repeated measurements. Changing the plotting labels does not change the independence assumption.
Further reading
Section titled “Further reading”R’s t-test documentation and SciPy’s independent-samples test describe Welch estimates and intervals. Rochon, Gondan, and Kieser studies why a normality pretest does not validate the selected analysis. The assumptions guide shows diagnostics without automatic test selection.