Skip to content

Simple Linear Regression

Correlation says how closely two variables move together. Regression fits the line and gives its equation: a slope in the units of the measurement, with a confidence interval, and a prediction for a new sample. This page models cell viability as a function of gene expression, in R and Python.

Use it for a continuous outcome that changes with a numeric predictor, when you want the size of the change per unit of the predictor or a prediction. The model assumes that the mean of the outcome follows a straight line in the predictor, that the samples are independent, and that the residuals have the same spread along the line. The intervals and p-values also assume residuals that are close to normal.

Download regression.csv into your working directory. The invented table has 50 rows, one per independent sample, and two columns: expression, the log2 expression of one gene, and viability, the percentage of viable cells.

The values come from a simulation with a known answer: an intercept of 90, a slope of -5, and a residual standard deviation of 8. A real experiment does not supply these numbers, but they help you judge the estimates below.

library(ggplot2)
regression <- read.csv("regression.csv")
dir.create("outputs", showWarnings = FALSE)
cat(sprintf("%d samples, columns: %s\n", nrow(regression),
paste(names(regression), collapse = ", ")))
cat(sprintf("expression from %.2f to %.2f\n", min(regression$expression),
max(regression$expression)))
50 samples, columns: expression, viability
expression from 2.15 to 9.96

lm() in R and ols() in statsmodels fit the line by least squares. The code prints one row per coefficient, with the estimate, its standard error, the t statistic, the p-value, and the 95% confidence interval. Two more lines give the residual standard error and R-squared.

fit <- lm(viability ~ expression, data = regression)
coef_table <- cbind(coef(summary(fit)), confint(fit))
print(coef_table, digits = 4)
cat(sprintf("Residual standard error %.3f on %d degrees of freedom\n",
sigma(fit), df.residual(fit)))
cat(sprintf("R-squared %.3f\n", summary(fit)$r.squared))
Estimate Std. Error t value Pr(>|t|) 2.5 % 97.5 %
(Intercept) 87.132 2.6373 33.04 1.139e-34 81.830 92.435
expression -4.585 0.4061 -11.29 4.110e-15 -5.401 -3.768
Residual standard error 6.837 on 48 degrees of freedom
R-squared 0.726

Both languages solve the same least-squares problem, so the two tabs print the same fit.

The slope is -4.585. A sample with one more unit of expression has, on average, a viability about 4.6 percentage points lower, and slopes from -5.40 to -3.77 are compatible with the data. That interval includes the simulated slope of -5.

The p-value of the slope is 4.1e-15. It is the probability of a t statistic at least as far from zero as -11.29 when the true slope is zero and the model assumptions hold. A flat line fits these data poorly. The p-value is not the probability that the slope is zero, and it does not measure how steep the line is. The interval carries the size.

The intercept, 87.13, is the predicted viability at an expression of zero. No sample has an expression below 2.15, so the intercept is an extrapolation, and its interval is only as good as the assumption that the line stays straight down to zero.

The residual standard error, 6.84, is the standard deviation of the samples around the line, in percentage points of viability. R-squared is 0.726, so the line accounts for about 73% of the variance of viability.

The figure shows the fitted line with its 95% confidence band. geom_smooth() computes the band in R. In Python, get_prediction() returns the fitted mean and its interval for each row of a grid of expression values.

fit_plot <- ggplot(regression, aes(expression, viability)) +
geom_point(color = "#69b3a2", alpha = 0.8, size = 2) +
geom_smooth(method = "lm", formula = y ~ x, level = 0.95,
color = "#1f4e5f", fill = "#1f4e5f", alpha = 0.2) +
labs(x = "Expression (log2)", y = "Viability (%)") +
theme_classic(base_size = 12)
ggsave("outputs/regression-fit-r.png", fit_plot, width = 5, height = 4,
dpi = 150)

Scatter of viability against expression for 50 samples, drawn with ggplot2, with the falling least-squares line and a narrow shaded 95% confidence band that widens toward both ends.

The residuals carry the assumptions of the model. Plot them against the fitted values and look for two patterns. A curve means that the mean does not follow a straight line. A funnel means that the spread changes with the fitted value.

residuals_table <- data.frame(fitted = fitted(fit), residual = resid(fit))
residual_plot <- ggplot(residuals_table, aes(fitted, residual)) +
geom_point(color = "#69b3a2", alpha = 0.8, size = 2) +
geom_hline(yintercept = 0, linetype = "dashed", color = "#1f4e5f") +
labs(x = "Fitted viability (%)", y = "Residual (%)") +
theme_classic(base_size = 12)
ggsave("outputs/regression-resid-r.png", residual_plot, width = 5,
height = 4, dpi = 150)

Residuals against fitted viability for 50 samples, drawn with ggplot2. The points scatter around the dashed zero line with no curve, and the spread is somewhat wider at low fitted values.

The residuals scatter around zero across the whole range, with no curve, so the plot gives no reason to doubt the straight line. The spread looks somewhat wider on the left than on the right. The simulation used one standard deviation for every sample, so this much unevenness arises by chance in 50 points.

A real table has no answer key. A spread that widens steadily across the range would be a reason to model the variance or to report heteroscedasticity-consistent standard errors, and a plot that shows neither pattern is compatible with the model without proving it.

A fitted line answers two different questions about an expression of 6. The confidence interval for the mean covers the average viability of all samples with that expression. The prediction interval covers the viability of one new sample.

new_sample <- data.frame(expression = 6)
mean_interval <- predict(fit, new_sample, interval = "confidence")
new_interval <- predict(fit, new_sample, interval = "prediction")
cat(sprintf("Predicted viability at expression 6: %.2f\n",
mean_interval[1, "fit"]))
cat(sprintf("95%% confidence interval for the mean: [%.2f, %.2f]\n",
mean_interval[1, "lwr"], mean_interval[1, "upr"]))
cat(sprintf("95%% prediction interval for one sample: [%.2f, %.2f]\n",
new_interval[1, "lwr"], new_interval[1, "upr"]))
Predicted viability at expression 6: 59.62
95% confidence interval for the mean: [57.68, 61.57]
95% prediction interval for one sample: [45.74, 73.51]

Both intervals sit around the same prediction, 59.62. The confidence interval for the mean, 57.68 to 61.57, carries only the uncertainty of the fitted line, so it narrows as the sample size grows. The prediction interval, 45.74 to 73.51, adds the scatter of single samples around the line, so it never narrows below about two residual standard errors on each side, however many samples you fit.

Quote the prediction interval when the question is about one future sample. Reporting 57.68 to 61.57 as the range for the next sample would understate that range about sevenfold. The prediction interval also leans on normal residuals more than the slope does, because it describes one sample and no averaging helps it.

The line describes expression values from 2.15 to 9.96. A prediction at an expression of 15 assumes that the same straight line continues there, and nothing in this table can check that.

R-squared does not check the shape of the model. A curved relationship can give an R-squared of 0.9 from a straight line that is wrong at both ends, and the residual plot is where the curve shows.

One sample far from the others in expression can pull the slope toward itself. The multiple regression page ranks samples by Cook’s distance to find such a sample.

The slope is an association. Samples with higher expression have lower viability in this table, and a third variable that raises expression and lowers viability would produce the same line. The multiple regression page works through that case.

The R linear model reference explains the formula interface, the intercept, and the components of a fitted model. The R predict.lm reference defines the confidence and prediction intervals used above.

The statsmodels OLS example covers model construction and prediction intervals in Python.

An Introduction to Statistical Learning derives the standard errors and intervals of simple linear regression in its third chapter and provides labs in R and Python. Continue with Multiple Regression to add predictors and adjust for a confounder.