---
webr:
packages: [dplyr, broom, broom.helpers, cardx, car, parameters, ggplot2, ggstats, patchwork, gtsummary] # gtsummary last (so its functions are not masked by other packages)
resources: [R/setup.R]
cell-options:
autorun: true
---
{{< include ./_extensions/r-wasm/live/_knitr.qmd >}}
# Plotting odds ratios (forest plots) {#sec-forest}
```{webr}
#| include: false
source("R/setup.R")
library(ggplot2)
library(patchwork)
```
Regression results are often presented not only as tables but also as **forest plots** (figures that line up estimates and confidence intervals as horizontal bars).
In this chapter, we turn the logistic regression from @sec-regression into a forest plot.
```{webr}
m <- glm(response ~ age + trt + grade + marker, data = trial, family = binomial)
t_mv <- tbl_regression(m, exponentiate = TRUE)
t_mv
```
## The simplest way: `plot()`
Passing a gtsummary regression table directly to `plot()` gives a forest plot (it uses the ggstats package internally).
```{webr}
plot(t_mv)
```
The result is a ggplot, so you can adjust it by adding ggplot2 functions with `+`.
```{webr}
plot(t_mv) +
ggplot2::labs(x = "Odds ratio (95% CI)") +
ggplot2::theme_bw()
```
## Table and figure side by side: `ggstats::ggcoef_table()`
In one line you can create the layout often seen in papers: "variables on the left, the plot in the middle, and OR (95% CI) and p-values on the right".
```{webr}
#| fig-width: 9
#| fig-height: 4
ggstats::ggcoef_table(m, exponentiate = TRUE)
```
::: {.callout-note}
`ggcoef_table()` takes **the model itself** (`m`), not a gtsummary table.
Variable labels are taken from the label attributes of the data.
:::
## Building it yourself: ggplot from the table data
When you want full control over the fine details of the appearance, extract the contents of the gtsummary table (`table_body`) and draw it with ggplot2.
The advantage is that **the numbers in the table and the figure are guaranteed to match**.
### Step 1: Extract the data
```{webr}
df <- t_mv$table_body |>
select(variable, var_type, row_type, reference_row, label,
estimate, conf.low, conf.high, p.value)
df
```
- `row_type == "label"`: the variable-name row (no estimate for categorical variables)
- `reference_row == TRUE`: the reference-category row (no estimate)
### Step 2: Prepare it for plotting
```{webr}
df_plot <- df |>
mutate(
# plot only a point for the reference category, at OR = 1
estimate = ifelse(reference_row %in% TRUE, 1, estimate),
# indent the levels of categorical variables
label = ifelse(row_type == "level", paste0(" ", label), label),
# create y coordinates so rows are ordered from the top
y = rev(seq_len(n())),
or_text = case_when(
reference_row %in% TRUE ~ "Reference",
is.na(estimate) ~ "",
TRUE ~ sprintf("%.2f (%.2f–%.2f)", estimate, conf.low, conf.high)
),
p_text = ifelse(is.na(p.value), "", style_pvalue(p.value, digits = 3))
)
df_plot |> select(label, y, estimate, or_text, p_text)
```
### Step 3: The forest plot
```{webr}
#| fig-height: 4
p_forest <- ggplot(df_plot, aes(x = estimate, y = y)) +
geom_vline(xintercept = 1, linetype = "dashed", colour = "grey50") +
geom_errorbar(aes(xmin = conf.low, xmax = conf.high), width = 0.2, na.rm = TRUE) +
geom_point(aes(shape = reference_row %in% TRUE), size = 3, na.rm = TRUE) +
scale_shape_manual(values = c(`FALSE` = 15, `TRUE` = 1), guide = "none") +
scale_x_log10() + # odds ratios on a log axis
scale_y_continuous(breaks = df_plot$y, labels = df_plot$label, expand = expansion(add = 0.6)) +
labs(x = "Odds ratio (95% CI, log scale)", y = NULL) +
theme_minimal(base_size = 13) +
theme(panel.grid.minor = element_blank(),
panel.grid.major.y = element_blank(),
axis.text.y = element_text(hjust = 0))
p_forest
```
::: {.callout-tip}
## Why a log axis?
An odds ratio of 2 (double) and one of 0.5 (half) represent the same effect size.
On an ordinary axis their distances from 1 look different (1 vs 0.5), but on a log axis they are symmetric around 1.
:::
### Step 4: Add columns of numbers on the right
With the patchwork package, place text columns for "OR (95% CI)" and "p-value" to the right of the plot.
```{webr}
#| fig-width: 9
#| fig-height: 4
text_col <- function(col, title) {
ggplot(df_plot, aes(x = 0, y = y, label = .data[[col]])) +
geom_text(hjust = 0, size = 4) +
scale_x_continuous(limits = c(0, 1), expand = c(0, 0)) +
scale_y_continuous(limits = range(df_plot$y) + c(-0.6, 0.6), expand = c(0, 0)) +
labs(title = title) +
theme_void(base_size = 13) +
theme(plot.title = element_text(face = "bold", size = 12))
}
p_forest + text_col("or_text", "OR (95% CI)") + text_col("p_text", "p-value") +
plot_layout(widths = c(3, 1.6, 0.8))
```
## Univariable and multivariable side by side
Drawing crude odds ratios (univariable) and adjusted odds ratios (multivariable) in the same figure makes the effect of confounding visible.
```{webr}
#| fig-height: 4.5
t_uv <- trial |>
tbl_uvregression(method = glm, y = response,
method.args = list(family = binomial),
exponentiate = TRUE,
include = c(age, trt, grade, marker))
both <- bind_rows(
t_uv$table_body |> mutate(model = "Univariable"),
t_mv$table_body |> mutate(model = "Multivariable")
) |>
filter(!is.na(estimate)) |> # only rows with an estimate
mutate(label = ifelse(row_type == "level", paste(var_label, label), label))
ggplot(both, aes(x = estimate, y = label, colour = model)) +
geom_vline(xintercept = 1, linetype = "dashed", colour = "grey50") +
geom_errorbar(aes(xmin = conf.low, xmax = conf.high), width = 0.2,
position = position_dodge(width = 0.5)) +
geom_point(size = 2.5, position = position_dodge(width = 0.5)) +
scale_x_log10() +
labs(x = "Odds ratio (95% CI)", y = NULL, colour = NULL) +
theme_minimal(base_size = 13) +
theme(legend.position = "bottom")
```
## Saving for a paper (on your own PC)
```r
# common in author guidelines: TIFF / 300 dpi / 17 cm wide
ggsave("figure2_forest.tiff", plot = last_plot(),
width = 17, height = 8, units = "cm", dpi = 300, compression = "lzw")
# vector format (does not degrade when enlarged)
ggsave("figure2_forest.pdf", width = 17, height = 8, units = "cm")
```
::: {.callout-important}
## Chapter summary
- Quick: `plot(tbl_regression(...))`; table + figure: `ggstats::ggcoef_table(model)`
- Full control: extract `tbl$table_body` and draw it with ggplot2 → table and figure numbers match
- Odds ratios and hazard ratios on a **log axis**, with a vertical dotted line at 1
- patchwork lets you place columns of numbers beside the plot
:::