set.seed(42)
n <- 800
cohort <- data.frame(
age = round(runif(n, 30, 75)),
female = rbinom(n, 1, 0.52),
bmi = rnorm(n, 26, 4.5),
smoker = rbinom(n, 1, 0.20),
activity = rbinom(n, 1, 0.45), # 1 = physically active
educ = factor(
sample(c("Low", "Medium", "High"), n,
replace = TRUE, prob = c(0.25, 0.45, 0.30)),
levels = c("Low", "Medium", "High")
)
)
cohort$sbp <- 110 +
0.40 * cohort$age -
4.50 * cohort$female +
0.50 * cohort$bmi -
2.00 * cohort$smoker -
2.50 * cohort$activity +
rnorm(n, sd = 8)
cohort$htn <- as.integer(cohort$sbp >= 140)Forest plots for regression models
This vignette goes from fitted models to forest plots. broom::tidy() turns a model into a data frame of estimates and confidence limits, which forrest() plots directly; any other function that returns such a data frame works as well. The last sections use marginaleffects to estimate average treatment effects by g-computation and inverse probability weighting.
Simulated cohort
All examples use one simulated cohort of 800 adults. Systolic blood pressure (SBP) rises with age and BMI and is lower in women, smokers and physically active people; hypertension is defined as SBP of 140 mmHg or more.
Several predictors from one model
broom::tidy(conf.int = TRUE) returns the columns estimate, conf.low and conf.high, which map onto the estimate, lower and upper arguments. Drop the intercept and replace the term names with readable labels.
fit_lm <- lm(sbp ~ age + female + bmi + smoker + activity, data = cohort)
coefs <- broom::tidy(fit_lm, conf.int = TRUE)
coefs <- coefs[coefs$term != "(Intercept)", ]
coefs$term <- c(
"Age (per 1 year)",
"Female sex",
"BMI (per 1 kg/m²)",
"Current smoker",
"Physically active"
)
coefs$coef_ci <- sprintf(
"%.2f (%.2f, %.2f)",
coefs$estimate, coefs$conf.low, coefs$conf.high
)
forrest(
coefs,
estimate = "estimate",
lower = "conf.low",
upper = "conf.high",
label = "term",
header = "Predictor",
cols = c("Coef (95% CI)" = "coef_ci"),
widths = c(3, 4, 2.5),
xlab = "Difference in SBP, mmHg (95% CI)",
stripe = TRUE
)
For a logistic model, exponentiate = TRUE in broom::tidy() returns odds ratios, and log_scale = TRUE in forrest() draws them on a log axis with the reference line at 1.
fit_glm <- glm(htn ~ age + female + bmi + smoker + activity,
data = cohort, family = binomial)
or_coefs <- broom::tidy(fit_glm, conf.int = TRUE, exponentiate = TRUE)
or_coefs <- or_coefs[or_coefs$term != "(Intercept)", ]
or_coefs$term <- c(
"Age (per 1 year)",
"Female sex",
"BMI (per 1 kg/m²)",
"Current smoker",
"Physically active"
)
or_coefs$or_text <- sprintf(
"%.2f (%.2f, %.2f)",
or_coefs$estimate, or_coefs$conf.low, or_coefs$conf.high
)
forrest(
or_coefs,
estimate = "estimate",
lower = "conf.low",
upper = "conf.high",
label = "term",
log_scale = TRUE,
header = "Predictor",
cols = c("OR (95% CI)" = "or_text"),
widths = c(3, 4, 2),
xlab = "Odds ratio for hypertension (95% CI)"
)
One exposure across adjustment sets
Papers often show how an association changes as covariates are added. Fit one model per adjustment set, keep the exposure’s row from each, and stack the rows.
m1 <- glm(htn ~ activity,
data = cohort, family = binomial)
m2 <- glm(htn ~ activity + age + female,
data = cohort, family = binomial)
m3 <- glm(htn ~ activity + age + female + bmi + smoker,
data = cohort, family = binomial)
extract_activity <- function(mod, label) {
row <- broom::tidy(mod, conf.int = TRUE, exponentiate = TRUE)
row <- row[row$term == "activity", ]
row$model <- label
row
}
adj_dat <- rbind(
extract_activity(m1, "Model 1: unadjusted"),
extract_activity(m2, "Model 2: + age, sex"),
extract_activity(m3, "Model 3: + BMI, smoking")
)
adj_dat$or_text <- sprintf(
"%.2f (%.2f, %.2f)",
adj_dat$estimate, adj_dat$conf.low, adj_dat$conf.high
)
forrest(
adj_dat,
estimate = "estimate",
lower = "conf.low",
upper = "conf.high",
label = "model",
log_scale = TRUE,
header = "Adjustment set",
cols = c("OR (95% CI)" = "or_text"),
widths = c(4, 3.5, 2),
xlab = "OR of hypertension, active vs inactive (95% CI)"
)
One exposure across several outcomes
To compare one exposure across outcomes, fit one model per outcome and stack the exposure rows. Differences from linear models and odds ratios from logistic models do not share a scale or a null value, so they go in separate plots: one with a linear axis and reference line at 0, one with a log axis and reference line at 1.
outcomes <- data.frame(
var = c("sbp", "bmi", "htn", "smoker"),
label = c("Systolic BP (mmHg)", "BMI (kg/m²)",
"Hypertension", "Current smoker"),
type = c("continuous", "continuous", "binary", "binary")
)
multi_out <- do.call(rbind, lapply(seq_len(nrow(outcomes)), function(i) {
o <- outcomes[i, ]
fml <- as.formula(paste(o$var, "~ activity + age + female"))
r <- if (o$type == "continuous") {
broom::tidy(lm(fml, data = cohort), conf.int = TRUE)
} else {
broom::tidy(glm(fml, data = cohort, family = binomial),
conf.int = TRUE, exponentiate = TRUE)
}
r <- r[r$term == "activity", ]
r$outcome <- o$label
r$type <- o$type
r
}))
multi_out$est_text <- sprintf(
"%.2f (%.2f, %.2f)",
multi_out$estimate, multi_out$conf.low, multi_out$conf.high
)
forrest(
multi_out[multi_out$type == "continuous", ],
estimate = "estimate",
lower = "conf.low",
upper = "conf.high",
label = "outcome",
header = "Outcome",
cols = c("Difference (95% CI)" = "est_text"),
widths = c(3.5, 3.5, 2.5),
xlab = "Difference, active vs inactive (95% CI)"
)
forrest(
multi_out[multi_out$type == "binary", ],
estimate = "estimate",
lower = "conf.low",
upper = "conf.high",
label = "outcome",
log_scale = TRUE,
header = "Outcome",
cols = c("OR (95% CI)" = "est_text"),
widths = c(3.5, 3.5, 2.5),
xlab = "Odds ratio, active vs inactive (95% CI)"
)
Exposure categories
A categorical exposure, here age quartiles, has a reference category with no estimate of its own. A row whose estimate is NA is drawn as a label without an interval, which keeps the reference category visible in its place; ref_label = TRUE appends “(Ref.)” to its label. The quartile labels are built from the cut points, so they stay correct if the data change.
breaks <- quantile(cohort$age, 0:4 / 4)
q_names <- sprintf("Q%d (%g–%g y)", 1:4, breaks[1:4], breaks[2:5])
cohort$age_q <- cut(cohort$age, breaks = breaks,
include.lowest = TRUE, labels = q_names)
fit_q <- glm(htn ~ age_q + female + bmi + smoker + activity,
data = cohort, family = binomial)
q_coefs <- broom::tidy(fit_q, conf.int = TRUE, exponentiate = TRUE)
q_coefs <- q_coefs[startsWith(q_coefs$term, "age_q"), ]
q_plot <- data.frame(
label = q_names,
estimate = c(NA, q_coefs$estimate),
conf.low = c(NA, q_coefs$conf.low),
conf.high = c(NA, q_coefs$conf.high)
)
q_plot$or_ci <- ifelse(
is.na(q_plot$estimate),
"1.00",
sprintf("%.2f (%.2f, %.2f)",
q_plot$estimate, q_plot$conf.low, q_plot$conf.high)
)
forrest(
q_plot,
estimate = "estimate",
lower = "conf.low",
upper = "conf.high",
label = "label",
ref_label = TRUE,
log_scale = TRUE,
header = "Age quartile",
cols = c("OR (95% CI)" = "or_ci"),
widths = c(3, 4, 2),
xlab = "OR for hypertension (95% CI)"
)
Average treatment effects by g-computation
Parametric g-computation estimates the average treatment effect (ATE) by predicting every person’s outcome twice, once as if active and once as if inactive, and averaging the differences. marginaleffects::avg_comparisons() does this in one call. Here the outcome model lets the effect of activity vary with each covariate, and the ATE is estimated overall and within strata of sex and education by averaging over the people in each stratum.
library(marginaleffects)
fit_sbp <- lm(
sbp ~ activity * (age + female + bmi + smoker + educ),
data = cohort
)
strata <- list(
list(stratum = "Overall", label = "Overall",
rows = rep(TRUE, n), is_sum = TRUE),
list(stratum = "Sex", label = "Female",
rows = cohort$female == 1, is_sum = FALSE),
list(stratum = "Sex", label = "Male",
rows = cohort$female == 0, is_sum = FALSE),
list(stratum = "Education", label = "Low",
rows = cohort$educ == "Low", is_sum = FALSE),
list(stratum = "Education", label = "Medium",
rows = cohort$educ == "Medium", is_sum = FALSE),
list(stratum = "Education", label = "High",
rows = cohort$educ == "High", is_sum = FALSE)
)
gcomp_dat <- do.call(rbind, lapply(strata, function(s) {
me <- avg_comparisons(fit_sbp, variables = "activity",
newdata = cohort[s$rows, ])
data.frame(
stratum = s$stratum,
label = s$label,
estimate = me$estimate,
lower = me$conf.low,
upper = me$conf.high,
is_sum = s$is_sum
)
}))
gcomp_dat$est_text <- sprintf(
"%.2f (%.2f, %.2f)",
gcomp_dat$estimate, gcomp_dat$lower, gcomp_dat$upper
)
forrest(
gcomp_dat,
estimate = "estimate",
lower = "lower",
upper = "upper",
label = "label",
section = "stratum",
is_summary = "is_sum",
cols = c("ATE (95% CI)" = "est_text"),
widths = c(3.5, 4, 3),
header = "Stratum",
xlab = "ATE of physical activity on SBP, mmHg (95% CI)"
)
Comparing g-computation with inverse probability weighting
Inverse probability weighting (IPW) models who is active rather than how SBP depends on the covariates. Each person is weighted by the inverse of the probability of the activity level they were observed to have, which balances the measured confounders between active and inactive people. Following the marginaleffects IPW chapter, the outcome model is refitted with these weights, and avg_comparisons() averages the contrasts with the same weights.
Plotting both estimators in one figure shows whether they agree. Each stratum has two rows, one per method, so dodge = TRUE draws them as a pair of intervals within one band and cols_by_group = TRUE gives each method its own text column.
ps_mod <- glm(activity ~ age + female + bmi + smoker + educ,
data = cohort, family = binomial)
cohort$ps <- predict(ps_mod, type = "response")
cohort$ipw <- ifelse(cohort$activity == 1, 1 / cohort$ps, 1 / (1 - cohort$ps))
# Truncate the weights at their 1st and 99th percentiles
cohort$ipw_t <- pmin(pmax(cohort$ipw, quantile(cohort$ipw, 0.01)),
quantile(cohort$ipw, 0.99))
fit_sbp_ipw <- lm(
sbp ~ activity * (age + female + bmi + smoker + educ),
data = cohort, weights = ipw_t
)
compare_dat <- do.call(rbind, lapply(strata, function(s) {
nd <- cohort[s$rows, ]
gc <- avg_comparisons(fit_sbp, variables = "activity", newdata = nd)
ipw <- avg_comparisons(fit_sbp_ipw, variables = "activity",
wts = "ipw_t", newdata = nd)
data.frame(
label = s$label,
method = c("G-computation", "IPW"),
estimate = c(gc$estimate, ipw$estimate),
lower = c(gc$conf.low, ipw$conf.low),
upper = c(gc$conf.high, ipw$conf.high),
is_sum = s$is_sum
)
}))
est_text <- sprintf("%.2f (%.2f, %.2f)", compare_dat$estimate,
compare_dat$lower, compare_dat$upper)
compare_dat$text_gc <- ifelse(compare_dat$method == "G-computation",
est_text, "")
compare_dat$text_ipw <- ifelse(compare_dat$method == "IPW", est_text, "")
forrest(
compare_dat,
estimate = "estimate",
lower = "lower",
upper = "upper",
label = "label",
group = "method",
is_summary = "is_sum",
dodge = TRUE,
cols_by_group = TRUE,
cols = c("G-computation (95% CI)" = "text_gc",
"IPW (95% CI)" = "text_ipw"),
widths = c(3, 3.5, 2.5, 2.5),
header = "Stratum",
xlab = "ATE of physical activity on SBP, mmHg (95% CI)"
)
The IPW intervals treat the weights as known. They ignore the uncertainty from estimating the propensity score; a bootstrap over both steps would account for it.
Estimates over time
Analyses that produce one estimate per time point, such as distributed lag models, life-course analyses and repeated measures, give a data frame in which time is one more column. section, group and dodge arrange them like any other grouping.
Distributed lag models
A distributed lag model estimates the association at each lag between exposure and outcome. Here section = "exposure" groups the lags under each exposure, and the cumulative estimate over all lags closes each section as a diamond.
set.seed(2025)
make_lags <- function(pattern) {
se <- runif(length(pattern), 0.03, 0.06)
est <- pattern + rnorm(length(pattern), sd = 0.02)
data.frame(
estimate = est,
lower = est - 1.96 * se,
upper = est + 1.96 * se
)
}
lag_labels <- paste("Lag", 0:6, "(weeks)")
dlm_dat <- rbind(
data.frame(exposure = "PM2.5", lag = lag_labels, is_sum = FALSE,
make_lags(c(0.04, 0.11, 0.10, 0.06, 0.03, 0.01, 0.00))),
data.frame(exposure = "PM2.5", lag = "Cumulative", is_sum = TRUE,
estimate = 0.35, lower = 0.18, upper = 0.52),
data.frame(exposure = "Road noise", lag = lag_labels, is_sum = FALSE,
make_lags(c(0.09, 0.05, 0.02, 0.01, 0.00, -0.01, 0.00))),
data.frame(exposure = "Road noise", lag = "Cumulative", is_sum = TRUE,
estimate = 0.16, lower = 0.04, upper = 0.28),
data.frame(exposure = "Green space", lag = lag_labels, is_sum = FALSE,
make_lags(c(-0.02, -0.04, -0.07, -0.09, -0.10, -0.09, -0.08))),
data.frame(exposure = "Green space", lag = "Cumulative", is_sum = TRUE,
estimate = -0.49, lower = -0.68, upper = -0.30)
)
dlm_dat$est_text <- sprintf("%.2f (%.2f, %.2f)",
dlm_dat$estimate, dlm_dat$lower, dlm_dat$upper)
forrest(
dlm_dat,
estimate = "estimate",
lower = "lower",
upper = "upper",
label = "lag",
section = "exposure",
is_summary = "is_sum",
header = "Lag",
cols = c("Coef (95% CI)" = "est_text"),
widths = c(3.5, 4, 2.8),
xlab = "Difference in SBP per IQR increase, mmHg (95% CI)"
)
Life-course analysis by stage
A life-course analysis estimates the same associations at several developmental stages. With section = "life_stage" each stage is a section listing the exposures, and group = "exposure" gives each exposure the same colour in every stage.
set.seed(99)
stage_row <- function(exposure, life_stage, est, se) {
est <- est + rnorm(1, sd = 0.01)
data.frame(
life_stage = life_stage,
exposure = exposure,
estimate = est,
lower = est - 1.96 * se,
upper = est + 1.96 * se
)
}
lc_dat <- rbind(
stage_row("Noise exposure", "Prenatal", 0.08, 0.03),
stage_row("Green space access", "Prenatal", -0.05, 0.04),
stage_row("Traffic-related air", "Prenatal", 0.06, 0.03),
stage_row("Noise exposure", "Early childhood", 0.12, 0.04),
stage_row("Green space access", "Early childhood", -0.09, 0.05),
stage_row("Traffic-related air", "Early childhood", 0.10, 0.04),
stage_row("Noise exposure", "Mid-childhood", 0.15, 0.05),
stage_row("Green space access", "Mid-childhood", -0.13, 0.05),
stage_row("Traffic-related air", "Mid-childhood", 0.14, 0.05),
stage_row("Noise exposure", "Adolescence", 0.09, 0.04),
stage_row("Green space access", "Adolescence", -0.07, 0.05),
stage_row("Traffic-related air", "Adolescence", 0.08, 0.04)
)
forrest(
lc_dat,
estimate = "estimate",
lower = "lower",
upper = "upper",
label = "exposure",
section = "life_stage",
group = "exposure",
legend_pos = NULL,
header = "Exposure",
xlab = "Difference in SBP per IQR increase, mmHg (95% CI)"
)
The colour legend is turned off with legend_pos = NULL because the labels already name the exposures.
Life-course analysis by exposure
To compare stages within each exposure instead, sort the same data by exposure, label the rows by exposure, colour them by stage, and dodge the stages within each exposure’s band.
stages <- c("Prenatal", "Early childhood", "Mid-childhood", "Adolescence")
lc_by_exposure <- lc_dat[order(lc_dat$exposure,
match(lc_dat$life_stage, stages)), ]
forrest(
lc_by_exposure,
estimate = "estimate",
lower = "lower",
upper = "upper",
label = "exposure",
group = "life_stage",
dodge = TRUE,
header = "Exposure",
xlab = "Difference in SBP per IQR increase, mmHg (95% CI)"
)
Saving plots
save_forrest(
file = "regression_forest.pdf",
plot = function() {
forrest(
coefs,
estimate = "estimate",
lower = "conf.low",
upper = "conf.high",
label = "term",
stripe = TRUE,
xlab = "Difference in SBP, mmHg (95% CI)"
)
},
width = 9,
height = 5
)