Hypothesis Testing
A two-group test starts from a null model, usually “both groups have the same mean”, and asks how surprising the observed difference would be if that model were true. The p-value is that tail probability. It is not the probability that the null model is true, and it carries no information about the size of the difference, so this page prints the mean difference and its 95% confidence interval next to each p-value.
The example compares the log2 expression of one gene between control samples and treated samples. The R and Python tabs run the same analysis, and your choice of tab carries down the page.
Get the data
Section titled “Get the data”Download expression.csv into your working directory. The invented table has 24 rows and three columns: sample, group (control or treated), and expression, a log2 expression value. Each row is a different sample, so the two groups are independent and each sample is one experimental unit.
library(ggpubr)
samples <- read.csv("expression.csv")control <- samples$expression[samples$group == "control"]treated <- samples$expression[samples$group == "treated"]dir.create("outputs", showWarnings = FALSE)
cat(sprintf("control: n = %d, mean = %.3f, SD = %.3f\n", length(control), mean(control), sd(control)))cat(sprintf("treated: n = %d, mean = %.3f, SD = %.3f\n", length(treated), mean(treated), sd(treated)))control: n = 12, mean = 5.050, SD = 0.207treated: n = 12, mean = 6.358, SD = 0.268from pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdimport seaborn as snsfrom scipy import stats
samples = pd.read_csv("expression.csv")control = samples.loc[samples["group"] == "control", "expression"]treated = samples.loc[samples["group"] == "treated", "expression"]output = Path("outputs")output.mkdir(exist_ok=True)
print(f"control: n = {len(control)}, mean = {control.mean():.3f}, " f"SD = {control.std():.3f}")print(f"treated: n = {len(treated)}, mean = {treated.mean():.3f}, " f"SD = {treated.std():.3f}")control: n = 12, mean = 5.050, SD = 0.207treated: n = 12, mean = 6.358, SD = 0.268Each group has 12 samples. The treated mean sits about 1.3 log2 units above the control mean, and the two standard deviations, 0.207 and 0.268, are of similar size.
Compare two means with Welch’s t-test
Section titled “Compare two means with Welch’s t-test”The two-sample t-test compares two group means. Student’s version assumes that both groups share one variance. Welch’s version drops that assumption and loses little when the variances happen to be equal, and R’s t.test() runs it by default. SciPy runs Student’s test by default, so the Python code sets equal_var=False.
The treated group goes first in the call, which makes the reported difference treated minus control.
welch <- t.test(treated, control)difference <- mean(treated) - mean(control)cat(sprintf("Welch t = %.3f, df = %.2f, p = %.3g\n", welch$statistic, welch$parameter, welch$p.value))cat(sprintf("Mean difference %.3f, 95%% CI [%.3f, %.3f]\n", difference, welch$conf.int[1], welch$conf.int[2]))cat(sprintf("Fold change %.2f, 95%% CI [%.2f, %.2f]\n", 2^difference, 2^welch$conf.int[1], 2^welch$conf.int[2]))Welch t = 13.396, df = 20.67, p = 1.18e-11Mean difference 1.308, 95% CI [1.105, 1.512]Fold change 2.48, 95% CI [2.15, 2.85]welch = stats.ttest_ind(treated, control, equal_var=False)interval = welch.confidence_interval(0.95)difference = treated.mean() - control.mean()print(f"Welch t = {welch.statistic:.3f}, df = {welch.df:.2f}, " f"p = {welch.pvalue:.3g}")print(f"Mean difference {difference:.3f}, " f"95% CI [{interval.low:.3f}, {interval.high:.3f}]")print(f"Fold change {2 ** difference:.2f}, " f"95% CI [{2 ** interval.low:.2f}, {2 ** interval.high:.2f}]")Welch t = 13.396, df = 20.67, p = 1.18e-11Mean difference 1.308, 95% CI [1.105, 1.512]Fold change 2.48, 95% CI [2.15, 2.85]Both languages return t = 13.396 on 20.67 degrees of freedom. The fractional degrees of freedom are Welch’s adjustment for two variances that are estimated separately. A p-value of 1.18e-11 says that a difference this large would almost never appear if the two groups shared one mean.
The second line is the result to report. Treated samples are 1.308 log2 units above control on average, and mean differences from 1.105 to 1.512 log2 units are compatible with the data. A difference of log2 values is a log2 fold change, so the third line converts it: treatment raises expression about 2.48 fold, with an interval from 2.15 to 2.85 fold. That fold change is a ratio of geometric means, because the averages were taken on the log scale.
Draw the comparison
Section titled “Draw the comparison”A boxplot with every sample drawn as a point shows what the test compared. In R, ggboxplot() from ggpubr draws the boxes and the points, and stat_compare_means() runs the named test on the plotted groups and draws a bracket with its p-value. ggpubr loads ggplot2, so labs(), theme(), and ggsave() work without a second library() call.
By default, ggpubr jitters the points in both directions, which moves each sample off its measured value. The jitter entry of add.params replaces that with a sideways jitter only, and its seed keeps the figure identical from run to run.
In Python, seaborn draws the boxes and the points, and a short helper adds the bracket with Matplotlib. The helper takes the p-value as an argument, so the rank test further down reuses it. seaborn jitters sideways only, and the helper fixes the NumPy seed that the jitter draws from.
point_jitter <- position_jitter(width = 0.2, height = 0, seed = 1)welch_plot <- ggboxplot(samples, x = "group", y = "expression", fill = "group", palette = c("#e07a5f", "#69b3a2"), add = "jitter", add.params = list(jitter = point_jitter)) + stat_compare_means(comparisons = list(c("control", "treated")), method = "t.test", label = "p.format") + labs(x = NULL, y = "Expression (log2)", title = "Welch t-test") + theme(legend.position = "none")ggsave("outputs/ttest-boxplot-r.png", welch_plot, width = 5, height = 4, dpi = 150)
def boxplot_with_bracket(data, p_value, title, path): """Draw expression by group with a bracket that carries a p-value.
Args: data: Table with the columns ``group`` and ``expression``. p_value: The p-value to print above the bracket. title: The title of the figure, which names the test. path: The path of the PNG file to write.
Returns: The path of the PNG file. """ np.random.seed(1) figure, axes = plt.subplots(figsize=(5, 4)) sns.boxplot(data=data, x="group", y="expression", hue="group", palette=["#e07a5f", "#69b3a2"], legend=False, width=0.5, fliersize=0, ax=axes) sns.stripplot(data=data, x="group", y="expression", color="black", alpha=0.6, ax=axes) base = data["expression"].max() + 0.25 axes.plot([0, 0, 1, 1], [base, base + 0.1, base + 0.1, base], linewidth=1.2, color="black") axes.text(0.5, base + 0.12, f"p = {p_value:.2g}", ha="center", va="bottom") axes.set_ylim(top=base + 0.6) axes.set_xlabel("") axes.set_ylabel("Expression (log2)") axes.set_title(title) figure.tight_layout() figure.savefig(path, dpi=150) plt.close(figure) return path
boxplot_with_bracket(samples, welch.pvalue, "Welch t-test", output / "ttest-boxplot-python.png")
The two groups do not overlap: the lowest treated sample is above the highest control sample. Name the test in the title or the legend whenever a figure carries a p-value, because a bare number on a bracket does not say which null model it tests.
Compare ranks with the Wilcoxon rank-sum test
Section titled “Compare ranks with the Wilcoxon rank-sum test”The Wilcoxon rank-sum test, which SciPy calls the Mann-Whitney U test, replaces the measurements with their ranks. Its null model is that both groups come from one distribution, and it responds to one departure in particular: values from one group tend to be larger than values from the other. That question differs from a difference in means. The answer becomes a statement about medians or a location shift only when the two distributions have the same shape.
Choose the rank test because that question fits the experiment, and choose before you see which test gives the smaller p-value. A small p-value from a normality test is not a reason to switch, as the assumption diagnostics page explains.
Several samples share an expression value. From version 4.6, R computes an exact conditional p-value for tied data by default. SciPy uses a normal approximation with a continuity correction when a group has more than 8 samples or the data have ties, and exact = FALSE asks R for that same approximation. The R code prints both p-values.
exact_test <- wilcox.test(treated, control)rank_test <- wilcox.test(treated, control, exact = FALSE)pair_count <- length(treated) * length(control)cat(sprintf("Wilcoxon W = %.0f of %d pairs\n", rank_test$statistic, pair_count))cat(sprintf("exact p = %.3g, normal approximation p = %.3g\n", exact_test$p.value, rank_test$p.value))cat(sprintf("Probability that treated exceeds control: %.2f\n", rank_test$statistic / pair_count))Wilcoxon W = 144 of 144 pairsexact p = 7.4e-07, normal approximation p = 3.56e-05Probability that treated exceeds control: 1.00rank_test = stats.mannwhitneyu(treated, control, alternative="two-sided")pair_count = len(treated) * len(control)print(f"Mann-Whitney U = {rank_test.statistic:.0f} of {pair_count} pairs, " f"p = {rank_test.pvalue:.3g}")print("Probability that treated exceeds control: " f"{rank_test.statistic / pair_count:.2f}")Mann-Whitney U = 144 of 144 pairs, p = 3.56e-05Probability that treated exceeds control: 1.00W in R and U in SciPy are the same number. It counts the pairs of one treated and one control sample in which the treated value is the higher one, and a tie counts as half a pair. There are 12 × 12 = 144 such pairs, and the treated sample is higher in all 144. The statistic divided by the number of pairs estimates the probability that a treated sample exceeds a control sample, here 1.00, and that proportion is the effect size to report beside a rank test.
The exact p-value is 7.4e-07, and the normal approximation gives 3.56e-05. The two differ by a factor of about 48 because the approximation is poor this far into the tail with 12 samples per group. Both are far larger than the 1.18e-11 of the t-test. Ranks record the order of the samples and discard the distances between them. With complete separation the ranks cannot become more extreme, so neither p-value would change however far the treated group moved above control.
The same boxplot can carry the rank test. In R, the method argument changes to "wilcox.test", and method.args passes exact = FALSE through to it. Both figures then carry the approximate p-value, so the two tabs show the same number. In Python, the helper takes the new p-value and title.
rank_plot <- ggboxplot(samples, x = "group", y = "expression", fill = "group", palette = c("#e07a5f", "#69b3a2"), add = "jitter", add.params = list(jitter = point_jitter)) + stat_compare_means(comparisons = list(c("control", "treated")), method = "wilcox.test", method.args = list(exact = FALSE), label = "p.format") + labs(x = NULL, y = "Expression (log2)", title = "Wilcoxon rank-sum test") + theme(legend.position = "none")ggsave("outputs/wilcox-boxplot-r.png", rank_plot, width = 5, height = 4, dpi = 150)
boxplot_with_bracket(samples, rank_test.pvalue, "Mann-Whitney U test", output / "wilcox-boxplot-python.png")
Both p-values are small because the invented groups do not overlap. Two tests that agree do not show that the design is sound. Whether the samples are independent, and whether the sample is the experimental unit, depends on how the experiment was run, and no test on this page can check it.
Report the result
Section titled “Report the result”Lead with the estimate and its interval, in the units of the measurement, then give the test and the group sizes: “Treated samples had higher expression than control samples (mean difference 1.31 log2 units, 95% CI 1.11 to 1.51; Welch’s t-test, t = 13.40, df = 20.67, p = 1.2e-11; 12 samples per group).”
Both tests on this page assume independent samples. When the same samples are measured before and after treatment, the two columns are paired, and an unpaired test treats them as unrelated. Use a paired analysis for that design; the paired tests page covers it.
Scientific references
Section titled “Scientific references”Welch, 1947 extends Student’s t-test to groups whose population variances differ.
Wilcoxon, 1945 introduces the comparison of two groups through the sums of their ranks.
Mann and Whitney, 1947 describe the U statistic as a test of whether one of two random variables tends to be larger than the other.
Further reading
Section titled “Further reading”The R documentation of t.test() describes the arguments that this page leaves at their defaults: var.equal for Student’s test, conf.level for the coverage of the interval, and alternative for a one-sided test.
The SciPy documentation of ttest_ind() describes equal_var, alternative, and the confidence_interval() method of the result, which returns the interval of the mean difference.
The ASA statement on p-values gives six principles for reading a p-value. Two of them underlie this page: a p-value does not measure the probability that the tested hypothesis is true, and it does not measure the size of an effect.
The estimation statistics page reports the same kind of comparison as an effect size with a bootstrap interval. The two-group figure page draws the estimate and its interval next to the data.