Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
A forest plot in R is the primary data visualization technique used in biomedical, psychological, and epidemiological research to synthesize effect sizes from multiple independent studies into a unified meta-analytic display. Generating publication-grade forest plots in R enables investigators conducting a systematic review or meta-analysis to display point estimates, 95% confidence intervals, relative study weights, and pooled effect estimates with statistical precision.
In computational research, analysts primarily rely on the metafor package developed by Wolfgang Viechtbauer for comprehensive statistical modeling, or the forestplot package by Max Gordon and Thomas Lumley for custom tabular displays of regression coefficients and hazard ratios. A standardized forest plot provides immediate visual insight into between-study heterogeneity, precision of findings, and overall pooled significance.
What it is used for in research
Forest plots are indispensable across clinical epidemiology, evidence-based medicine, social sciences, and environmental health. When conducting a quantitative synthesis, researchers compare outcomes across diverse clinical trials or observational cohorts. Rather than relying on narrative summaries, a forest plot visually organizes study-level outcomes alongside a statistically weighted summary diamond.
Key research applications include:
- Two-Arm Comparative Trials: Evaluating clinical interventions using ratio metrics such as relative risks (RR), odds ratios (OR), and hazard ratios (HR), or difference metrics such as raw mean differences (MD) and standardized mean differences (SMD).
- Assessment of Between-Study Heterogeneity: Concurrently reporting Cochran’s Q, the I² statistic (reflecting the percentage of total variation across studies due to heterogeneity rather than chance), and τ² (the estimated between-study variance in random-effects models).
- Multivariable Regression Summaries: Presenting adjusted effect estimates across demographic or biomarker subgroups in observational epidemiological studies.
- Evidence Synthesis Quality Control: Complementing publication bias diagnostics such as a funnel plot by verifying whether smaller studies show systematic asymmetry compared to larger trials.
Generating forest plots in R for evidence synthesis
Understanding the distinction between an exploratory systematic review vs. meta-analysis is vital: while a systematic review identifies all relevant evidence through comprehensive literature screening, a meta-analysis uses statistical tools like R to quantitatively pool those findings. In R, generating a forest plot is not merely an aesthetic plotting exercise; it is directly linked to the mathematical structure of the fitted statistical model, guaranteeing that point marker sizes, interval widths, and the summary diamond reflect inverse-variance weights.
How to install or access it
Both primary packages are available directly from the Comprehensive R Archive Network (CRAN) and require no external commercial licenses or proprietary drivers.
To install the official CRAN releases, run the following commands in the R console:
# Install official CRAN packages
install.packages("metafor")
install.packages("forestplot")
Once installed, load the libraries into your active R session:
# Load packages into current session
library(metafor)
library(forestplot)
Official package documentation and reference materials are hosted on CRAN:
metaforCRAN page: https://cran.r-project.org/package=metaforforestplotCRAN page: https://cran.r-project.org/package=forestplot- Viechtbauer Metafor Project Portal: https://www.metafor-project.org/
Step-by-step instructions
The following step-by-step workflow demonstrates how to calculate effect sizes, fit a random-effects meta-analysis model, and construct a publication-ready forest plot in R using metafor, followed by an alternative workflow using forestplot.
-
Load dataset and calculate effect sizes using escalc():
For binary 2×2 clinical trial data (e.g. tuberculosis prevention trials from
dat.bcg), compute log risk ratios (measure = "RR") and their corresponding sampling variances (vi):library(metafor) # Load built-in BCG vaccine clinical trial dataset data(dat.bcg) # Calculate log risk ratios (yi) and sampling variances (vi) dat <- escalc( measure = "RR", ai = tpos, bi = tneg, ci = cpos, di = cneg, data = dat.bcg ) -
Fit a random-effects meta-analysis model using rma():
Fit a random-effects model using Restricted Maximum Likelihood (REML) estimation, which provides an unbiased estimate of the between-study variance τ²:
# Fit random-effects meta-analysis model via REML res <- rma(yi, vi, data = dat, method = "REML") # View statistical model summary summary(res) -
Generate the customized forest plot using forest():
Pass the fitted
resobject to the S3 methodforest.rma(). Configure horizontal axis boundaries (xlimandalim), exponentiate log risk ratios back to the natural ratio scale (atransf = exp), set tick marks (at), provide study labels (slab), display study weights (showweights = TRUE), and format column headers (header):# Configure graphical canvas margins and parameters par(mar = c(5, 4, 2, 2)) # Render publication-grade forest plot forest( res, xlim = c(-16, 6), alim = c(-2.5, 1.5), at = log(c(0.1, 0.25, 0.5, 1, 2, 4)), atransf = exp, slab = paste(dat$author, dat$year, sep = ", "), xlab = "Risk Ratio (logarithmic scale)", mlab = "RE Model for All Studies", showweights = TRUE, header = c("Study and Year", "Risk Ratio [95% CI]"), cex = 0.85, pch = 15, col = "darkblue", border = "darkblue" ) -
Add custom subheadings or text annotations:
Use base R graphics functions such as
text()to annotate column headers or subgroup divisions along the coordinate space established byxlim:# Add weight column header text(-2.8, 15, "Weight", font = 2, cex = 0.85)
Alternative workflow: forestplot in R for tabular regression data
When presenting multivariable regression coefficients, hazard ratios across clinical cohorts, or pre-calculated summary tables rather than an inverse-variance meta-analysis, the standalone forestplot package provides a flexible table-based layout:
library(forestplot)
library(dplyr)
# Construct tabular summary dataframe
reg_data <- data.frame(
subgroup = c("All Patients", "Age < 65", "Age >= 65", "Male", "Female"),
events = c("210/1000", "85/450", "125/550", "110/520", "100/480"),
HR = c(0.82, 0.74, 0.91, 0.79, 0.86),
lower = c(0.70, 0.58, 0.76, 0.63, 0.70),
upper = c(0.96, 0.94, 1.09, 0.99, 1.06)
)
# Render grid-based forest plot
reg_data %>%
forestplot(
labeltext = c(subgroup, events),
mean = HR,
lower = lower,
upper = upper,
zero = 1,
xlog = TRUE,
xlab = "Hazard Ratio (95% CI)",
boxsize = 0.2,
col = fpColors(box = "darkblue", line = "black", zero = "gray50")
)
Output and how to read it
Reading a forest plot accurately requires systematically evaluating each graphical element in accordance with the Cochrane Handbook for Systematic Reviews of Interventions:
- Vertical Reference Line (Line of No Effect): Placed at 1.0 for ratio effect sizes (such as relative risks, odds ratios, and hazard ratios) and at 0.0 for difference metrics (such as mean differences and standardized mean differences). If an individual study interval or the summary diamond touches or crosses this line, the observed effect is not statistically significant at the α = 0.05 level.
- Study Marker Boxes (Point Estimates): The horizontal center of each square represents the study’s observed effect size. The physical area of each square is proportional to the study’s statistical weight in the meta-analysis, which is inversely related to its sampling variance (1 / vi). Larger squares represent larger, more precise clinical trials.
- Horizontal Whiskers (Confidence Intervals): The horizontal lines extending outward from each marker represent the 95% confidence interval for that individual trial. Wide lines reflect small sample sizes and low precision; narrow lines reflect large cohorts and tight precision.
- Summary Polygon (Pooled Diamond): The diamond at the bottom represents the pooled meta-analytic effect across all included studies. The horizontal center of the diamond represents the pooled point estimate. The lateral left and right tips represent the lower and upper bounds of the pooled 95% confidence interval. If the lateral tips do not cross the vertical null line, the overall intervention demonstrates a statistically significant effect.
- Heterogeneity Metrics: Standard forest plots report Cochran’s Q test p-value, the I² index (where values around 25%, 50%, and 75% suggest low, moderate, and high heterogeneity, respectively), and τ² (the between-study variance in random-effects models).
Troubleshooting
When rendering forest plots in R, researchers frequently encounter common layout and numerical errors. Apply the following solutions:
- Study labels or numeric annotations are clipped off-screen: In
metafor::forest(), the coordinate space is controlled by thexlimargument. By default,xlimmay not allow enough horizontal space for lengthy author names on the left or multi-digit confidence intervals on the right. Expandxlim(e.g., settingxlim = c(-16, 6)while keepingalim = c(-2.5, 1.5)) to provide ample margin for text. - Negative tick values cause errors with atransf = exp: When using
atransf = expto exponentiate log ratios to natural ratios, specify tick marks in log space using positive ratio targets:at = log(c(0.1, 0.25, 0.5, 1, 2, 4)). Passing raw non-positive values tolog()producesNaNwarnings. - Mismatch between slab length and dataset rows: Ensure the character vector passed to
slabexactly matches the number of studies in the fitted model object (k). If studies were excluded duringrma()due to missing values, subset the label vector identically. - Accidentally passing standard errors (SE) instead of variance (vi) to rma(): The
rma()function expects sampling variance (vi = SE²) in its second argument by default. If your data contains standard errors, use the explicit parametersei = SEor square the values before fitting. - Low-resolution image exports for publication manuscripts: Never rely on screenshotting the RStudio plot viewer. Instead, wrap the plotting code between explicit high-resolution graphics device calls:
png("forest_plot.png", width = 2400, height = 1800, res = 300) forest(res, ...) dev.off()
Free alternatives
The following table compares open-source software packages and graphical tools available for generating forest plots in scientific research:
| Package / Tool | Environment | Primary Data Input | Automated Summary Diamond | Best Research Application |
|---|---|---|---|---|
| metafor | R (CRAN) | Raw 2×2 contingency counts or effect sizes (yi, vi) | Yes (automated via rma model object) | Comprehensive meta-analyses, meta-regressions, and multilevel random-effects modeling. |
| forestplot | R (CRAN) | Data frames with mean, lower, and upper bounds | Optional (custom polygon function) | Publication tables of multivariable regression models, hazard ratios, and clinical subgroup comparisons. |
| meta | R (CRAN) | Standard study data frames (metabin, metacont) | Yes (automated via meta object) | Standard Cochrane-style pairwise meta-analyses with automated subgroup formatting. |
| ggplot2 + geom_pointrange | R (CRAN) | Tidy data frames (tibbles) | Manual (custom geom_polygon geometry required) | Highly custom visual themes, multifaceted plots, and non-standard visual layouts. |
| RevMan (Review Manager) | Standalone / Web (Cochrane) | Structured systematic review entry forms | Yes (built-in Cochrane engine) | Authoring formal Cochrane systematic reviews with standardized protocol formatting. |
FAQ
How do I display study weights on a forest plot in R?
In metafor, add the argument showweights = TRUE inside the forest() function call. This adds a dedicated column showing the relative inverse-variance weight (as a percentage) contributed by each study to the overall pooled effect estimate.
What is the difference between metafor and the standalone forestplot package?
The metafor package is an integrated statistical meta-analysis suite that calculates effect sizes, fits fixed- and random-effects models, computes heterogeneity statistics, and automatically derives summary diamonds. The forestplot package is a general-purpose graphics tool that takes pre-calculated estimates and confidence intervals to produce publication-grade tables without performing underlying statistical modeling.
Why should I use atransf = exp when plotting risk ratios or odds ratios?
Statistical meta-analysis models for ratio metrics operate on the natural logarithmic scale (log RR or log OR) because log ratios are normally distributed and have symmetric standard errors. Using atransf = exp exponentiates the axis ticks and numeric annotations back to the natural ratio scale (where 1.0 represents no effect), making the results easily interpretable for clinical readers while preserving statistically symmetric confidence intervals.
How do I export a publication-ready forest plot from R?
Wrap your plotting commands in a graphics device call such as png("figure1.png", width = 2400, height = 1800, res = 300) for 300 DPI raster output, or pdf("figure1.pdf", width = 8, height = 6) for vector graphics, followed by dev.off().
Can I display subgroup analyses in a single forest plot in R?
Yes. In metafor, fit a meta-regression model with a categorical moderator using rma(yi, vi, mods = ~ factor(subgroup), data = dat), or split the dataset and generate separate summary polygons using addpoly() to display subgroup and overall pooled estimates on the same figure.
Sources
- Viechtbauer, W. (2010). Conducting meta-analyses in R with the metafor package. Journal of Statistical Software, 36(3), 1–48. CRAN documentation: https://cran.r-project.org/package=metafor (read 2026-11-11). Project portal: https://www.metafor-project.org/
- Gordon, M., and Lumley, T. (2023). forestplot: Advanced Forest Plot Using ‘grid’ Graphics. CRAN reference: https://cran.r-project.org/package=forestplot (read 2026-11-11).
- Higgins, J. P. T., Thomas, J., Chandler, J., Cumpston, M., Li, T., Page, M. J., and Welch, V. A. (Eds.). (2023). Cochrane Handbook for Systematic Reviews of Interventions (version 6.4), Chapter 10: Analysing data and undertaking meta-analyses. Cochrane: https://training.cochrane.org/handbook/current/chapter-10 (read 2026-11-11).
- Schwarzer, G. (2023). meta: General Package for Meta-Analysis. CRAN reference: https://cran.r-project.org/package=meta (read 2026-11-11).







