Descriptive Statistics & Distributions
Summarize each variable and plot its distribution before you fit a model. A few numbers give the center and the spread. A histogram shows what those numbers hide: skew, an isolated value, a second peak, or a column of counts that someone treated as a continuous measurement. This page works through 80 expression values and 80 read counts in R and Python.
Get the data
Section titled “Get the data”Download gene_expression.csv into your working directory. The invented table has 80 rows, one per sample, and three columns: a sample label, an expression value on the log2 scale, and a counts column of read counts. All 80 samples belong to one group, with no treatment and no batch.
library(ggplot2)
samples <- read.csv("gene_expression.csv")dir.create("outputs", showWarnings = FALSE)print(head(samples, 5)) sample expression counts1 S01 6.37 462 S02 4.75 443 S03 6.90 334 S04 7.13 325 S05 3.66 39from pathlib import Path
import matplotlib.pyplot as pltimport pandas as pdimport seaborn as snsfrom scipy import stats
samples = pd.read_csv("gene_expression.csv")output = Path("outputs")output.mkdir(exist_ok=True)print(samples.head(5)) sample expression counts0 S01 6.37 461 S02 4.75 442 S03 6.90 333 S04 7.13 324 S05 3.66 39Numeric summaries
Section titled “Numeric summaries”Two numbers describe the center of a variable. The mean is the average, and the median is the middle value of the sorted data. Two more describe the spread. The standard deviation measures the typical distance from the mean, and the interquartile range, or IQR, is the width of the middle half of the data.
print(summary(samples$expression))cat(sprintf("sd = %.3f, IQR = %.3f\n", sd(samples$expression), IQR(samples$expression))) Min. 1st Qu. Median Mean 3rd Qu. Max. 3.660 5.447 6.145 6.031 6.753 8.570sd = 0.929, IQR = 1.305print(samples["expression"].describe())quartiles = samples["expression"].quantile([0.25, 0.75])print(f"sd = {samples['expression'].std():.3f}, " f"IQR = {quartiles[0.75] - quartiles[0.25]:.3f}")count 80.000000mean 6.031000std 0.928916min 3.66000025% 5.44750050% 6.14500075% 6.752500max 8.570000Name: expression, dtype: float64sd = 0.929, IQR = 1.305The two languages agree. The mean is 6.031 and the median is 6.145, 0.11 log2 units apart, which is small beside a standard deviation of 0.929. The middle half of the samples spans 1.305 log2 units, from the first quartile at 5.447 to the third at 6.753.
Report the number of samples with every summary. A mean of 6.03 from 80 samples and a mean of 6.03 from 4 samples are different pieces of evidence.
Mean or median?
Section titled “Mean or median?”The mean uses the size of every value, so a few large values pull it up. The median uses only the order of the values and stays where it is. Raw expression shows the difference. Undo the log2 transform and summarize the same 80 samples on the linear scale.
linear <- 2^samples$expressioncat(sprintf("linear scale: mean = %.1f, median = %.1f\n", mean(linear), median(linear)))cat(sprintf("log2 scale: mean = %.3f, median = %.3f\n", mean(samples$expression), median(samples$expression)))cat(sprintf("2^(log2 mean) = %.1f\n", 2^mean(samples$expression)))linear scale: mean = 79.7, median = 70.8log2 scale: mean = 6.031, median = 6.1452^(log2 mean) = 65.4linear = 2 ** samples["expression"]print(f"linear scale: mean = {linear.mean():.1f}, " f"median = {linear.median():.1f}")print(f"log2 scale: mean = {samples['expression'].mean():.3f}, " f"median = {samples['expression'].median():.3f}")print(f"2^(log2 mean) = {2 ** samples['expression'].mean():.1f}")linear scale: mean = 79.7, median = 70.8log2 scale: mean = 6.031, median = 6.1452^(log2 mean) = 65.4On the linear scale the mean is 79.7 and the median is 70.8. The large values in the right tail pull the mean about 9 units above the median. On the log2 scale the same samples have a mean of 6.031 and a median of 6.145, so the two summaries nearly coincide. That symmetry is one reason to analyze expression on the log scale.
The scale also changes what a mean stands for. Two raised to the log2 mean is 65.4, the geometric mean, and it is well below the arithmetic mean of 79.7. Say which scale a reported mean comes from. When the mean and the median disagree, report the median with the quartiles, or summarize on the scale where the distribution is closer to symmetric.
Draw the distribution
Section titled “Draw the distribution”A histogram cuts the range into bins and counts the values in each bin. A density curve is a smoothed version of the same shape. The code below draws both for the log2 expression values.
histogram <- ggplot(samples, aes(x = expression)) + geom_histogram(aes(y = after_stat(density)), bins = 15, fill = "#69b3a2", color = "white") + geom_density(color = "#1f4e5f", linewidth = 1) + labs(x = "Expression (log2)", y = "Density", title = "Distribution of expression") + theme_minimal(base_size = 13)ggsave("outputs/hist-density-r.png", histogram, width = 5, height = 4, dpi = 150)
figure, axis = plt.subplots(figsize=(5, 4))sns.histplot(samples["expression"], bins=15, stat="density", color="#4c72b0", ax=axis)sns.kdeplot(samples["expression"], color="#1f2a44", ax=axis)axis.set(xlabel="Expression (log2)", ylabel="Density", title="Distribution of expression")figure.tight_layout()figure.savefig(output / "hist-density-python.png", dpi=150)plt.close(figure)
The values form one broad peak between 5 and 7. The highest value, 8.57, sits at the end of the right tail, and in both panels an empty bin separates it from the rest.
ggplot2 and seaborn place their 15 bins at different edges, so the bars differ between the tabs although the data are the same. Redraw the histogram with another number of bins before you read a dip between two bars as a second peak.
Read a normal Q-Q plot
Section titled “Read a normal Q-Q plot”A normal quantile-quantile plot, or Q-Q plot, sorts the values and plots them against the quantiles of a normal distribution. Points on the reference line mean that a normal distribution describes the values. Both ends curving away from the line signal tails that are heavier or lighter than normal, and a bow to one side signals skew.
qq_plot <- ggplot(samples, aes(sample = expression)) + stat_qq(color = "#69b3a2") + stat_qq_line(color = "#1f4e5f") + labs(x = "Theoretical normal quantiles", y = "Expression quantiles", title = "Normal Q-Q plot") + theme_minimal(base_size = 13)ggsave("outputs/qq-r.png", qq_plot, width = 5, height = 4, dpi = 150)
figure, axis = plt.subplots(figsize=(5, 4))stats.probplot(samples["expression"], dist="norm", plot=axis)axis.set(xlabel="Theoretical normal quantiles", ylabel="Expression quantiles", title="Normal Q-Q plot")figure.tight_layout()figure.savefig(output / "qq-python.png", dpi=150)plt.close(figure)
The points follow the line through the middle of the data. Between theoretical quantiles 1 and 2 they fall slightly below it, so the upper tail is a little shorter than a normal tail. The largest value, 8.57, breaks that pattern and lies on or above the line. The two tabs draw different reference lines: stat_qq_line() passes through the first and third quartiles, and probplot() fits a least-squares line to all 80 points.
This plot is compatible with a normal distribution for these 80 values. It does not prove one, because 80 points cannot rule out a mild departure.
A t-test or a linear model does not require a normal variable. The assumption concerns the errors of the model: the deviation of each sample from its own group mean, or from the fitted line. This table has one group, so the raw values differ from the errors only by a constant, and the plot above already shows the errors. A table with two groups is different. If the group means differ, the pooled values form a mixture with two centers, and their Q-Q plot bends even when the errors within each group are normal. Subtract the group means first and plot the residuals, as Checking Assumptions does.
That page also covers the Shapiro-Wilk test and its limit. A large p-value from a normality test means that the test did not detect a departure, and with a small sample it can miss a large one. No diagnostic test certifies the assumption, so keep the plot and judge how much the departure you see would move the estimate you care about.
Count data behaves differently
Section titled “Count data behaves differently”Read counts are whole numbers, they cannot be negative, and their variance is tied to their mean. A normal model has a separate parameter for the spread. A Poisson model has none: its variance equals its mean.
cat(sprintf("counts: mean = %.2f, variance = %.2f, range = %d to %d\n", mean(samples$counts), var(samples$counts), min(samples$counts), max(samples$counts)))count_plot <- ggplot(samples, aes(x = counts)) + geom_histogram(binwidth = 5, fill = "#e07a5f", color = "white") + labs(x = "Read counts", y = "Samples", title = "Distribution of read counts") + theme_minimal(base_size = 13)ggsave("outputs/counts-hist-r.png", count_plot, width = 5, height = 4, dpi = 150)counts: mean = 39.02, variance = 43.39, range = 25 to 56
print(f"counts: mean = {samples['counts'].mean():.2f}, " f"variance = {samples['counts'].var():.2f}, " f"range = {samples['counts'].min()} to {samples['counts'].max()}")figure, axis = plt.subplots(figsize=(5, 4))sns.histplot(samples["counts"], binwidth=5, color="#dd8452", ax=axis)axis.set(xlabel="Read counts", ylabel="Samples", title="Distribution of read counts")figure.tight_layout()figure.savefig(output / "counts-hist-python.png", dpi=150)plt.close(figure)counts: mean = 39.02, variance = 43.39, range = 25 to 56
The mean count is 39.02 and the variance is 43.39, close to the equality that a Poisson model implies. At a mean near 39 the histogram looks close to symmetric, so the shape alone does not reveal a count column. The whole-number values do, and so does a variance that follows the mean. A gene with a mean of 2 or 3 reads looks different: its counts pile up against zero.
The link between mean and variance is the first reason to keep raw counts out of a pooled t-test or an ordinary linear model. A group with a higher mean count has a higher variance too, so the single error variance of such a model describes neither group. Depth is the second reason: counts rise with the number of reads sequenced, and a count model accounts for depth with an offset. Sequencing counts from biological replicates usually vary more than a Poisson model allows, which is why DESeq2 and edgeR use the negative binomial distribution. Model counts with a count model. Count Regression fits the Poisson and the negative binomial model and checks the dispersion.
Report a summary
Section titled “Report a summary”Give the center, the spread, and the number of samples together: “log2 expression, mean 6.03 (SD 0.93), n = 80”. A mean alone hides how much the samples vary. For a skewed variable, give the median and the quartiles. For a count column, report the counts and model them as counts.
When a table holds several groups or batches, compute each summary and draw each histogram per group. A pooled summary of two groups with different means describes neither group.
Further reading
Section titled “Further reading”The pandas describe reference lists the statistics in the Python summary and the percentiles argument that changes the reported quantiles.
The R quantile reference defines nine quantile rules. R uses type 7 by default and pandas uses the same linear interpolation, which is why the two IQR values on this page agree. Other software can report a slightly different quartile for the same data.
The SciPy probplot reference explains how the Python Q-Q plot computes its theoretical quantiles and its fitted line.
Checking Assumptions moves from one variable to the residuals of a model with groups. Count Regression models the kind of column that the last section describes.