Forest plots using ggplot2 and patchwork

The basic plot

Frequent users of ggplot2 might prefer not to use forestploter but instead rely on more familiar packages. It is fairly straightforward to make a forest plot using ggplot2 and patchwork. First, let’s try to assemble a forest plot including a column of labels, columns with risk estimates in the intervention and control group, and a forest plot of risk ratios. The data are the same that were used for the simple plot, which readers are advised to look at before continuing:

library(data.table)
library(ggplot2)
library(patchwork)
library(dplyr)

# theme_void is used by default as axes, ticks etc. are superfluous
# to make stripes in the forest plot align across columns, the x-axis must exist - but we hide it
theme_set(
  theme_void(base_size = 15) +
    theme(
      axis.line.x = element_line(color = "transparent"),
      axis.text.x = element_text(color = "transparent"),
      axis.ticks.x = element_line(color = "transparent"),
      axis.ticks.length.x = unit(2, "mm"),
      plot.title = element_text(hjust = .5, face = "bold")
    )
)

# text size within the forest plot
tsize <- 6

dt <- fread("./data/SimpleFPdata.csv") |>
  mutate(
    # a variable used to control rows (y-axis) in the plot
    y = n() - row_number(),
    
    # which levels should have indentation (and not be bold face)
    indent = case_when(is.na(events1) | level == "Overall" ~ 0,
                       .default = 1),
    
    # adding indentation
    level = case_when(indent == 1 ~ paste("  ", level),
                      .default = level),
    
    # variable to control bold face vs. plain labeling
    boldface = case_when(indent == 0 ~ "bold",
                         .default = "plain")
  )

One simple way to make a forest plot using ggplot2 and patchwork is to simply make a plot for each column to be included, and then patching them together afterwards:

# column with labels, the x-value is arbitrary (also below)
labels <- ggplot(dt, aes(x = 0, y = y, label = level, fontface = boldface)) +
  # the labels should be left justified
  geom_text(hjust = 0, size = tsize) +
  # setting the minimum x-value to 0 [same as x-value in aes()] for aesthetic reasons
  coord_cartesian(xlim = c(0, 1))

# column with risk estimates in the intervention group
risk1 <- ggplot(dt, aes(x = 1, y = y, label = risk1)) +
  geom_text(size = tsize) +
  ggtitle("Risk (95% CI) in the\nintervention group")

# column with risk estimates in the control group
risk0 <- ggplot(dt, aes(x = 1, y = y, label = risk0)) +
  geom_text(size = tsize) +
  ggtitle("Risk (95% CI) in the\ncontrol group")

# forest plot of risk ratios
fp <- ggplot(dt, aes(x = rr, xmin = lcl, xmax = ucl, y = y)) +
  geom_vline(xintercept = 1, color = "grey", linetype = 2) +
  geom_pointrange(color = "#58508d", linewidth = 1.5) +
  # we need to show the x-axis for this particular plot
  theme(axis.line.x = element_line(color = "black"),
        axis.text.x = element_text(color = "black"),
        axis.ticks.x = element_line(color = "black"),
        axis.ticks.length = unit(2, "mm")) +
  ggtitle("\nRisk ratio with 95% CI")

# patching the columns together
forest_plot <- (labels | risk1 | risk0 | fp) +
  plot_layout(widths = c(1, 1, 1, 1.5))
Figure 1: Basic forest plot using ggplot2 and patchwork

So far so good, but there are no stripes. One observation before we add those: the second and third column are in principle made the same way so it would be sensible to construct these using a function, we will do that below.

Alternating stripes are easy to add to the individual column using geom_rect, on a derived data set:

# select every other row, here the even numbered rows
# to get event numbered rows filter on `y %% 2 == 1`
stripesdt <- dt |>
  filter(y %% 2 == 0)

Using this stripesdt we can make a function that will produce generic columns with text and stripes:

colfun <- function(var, title){

  col <- ggplot(dt, aes(x = 1, y = y, label = {{var}})) +
    # adding rectangles spanning the entire x-axis for half the rows
    geom_rect(data = stripesdt,
              aes(xmin = -Inf, xmax = Inf, ymin = y - .5, ymax = y + .5),
              fill = "#f6f1ff") +
    geom_text(size = tsize) +
    ggtitle(title)

  return(col)
}

We can now make a striped version of the column with labels; use colfun to make striped version of the risk-columns; make a striped version of the forest plot; and finally patch it all up:

labels_stripes <- ggplot(dt, aes(x = 0, y = y, label = level, fontface = boldface)) +
  geom_rect(data = stripesdt,
            aes(xmin = -Inf, xmax = Inf, ymin = y - .5, ymax = y + .5),
            fill = "#f6f1ff") +
  geom_text(hjust = 0, size = tsize) +
  coord_cartesian(xlim = c(0, 1))

risk1_stripes <- colfun(risk1, "Risk (95% CI) in the\nintervention group")
risk0_stripes <- colfun(risk0, "Risk (95% CI) in the\ncontrol group")

fp_stripes <- ggplot(dt, aes(x = rr, xmin = lcl, xmax = ucl, y = y)) +
  geom_rect(data = stripesdt,
            aes(xmin = -Inf, xmax = Inf, ymin = y - .5, ymax = y + .5),
            fill = "#f6f1ff") +
  geom_vline(xintercept = 1, color = "grey", linetype = 2) +
  geom_pointrange(color = "#58508d", linewidth = 1.5) +
  theme(axis.line.x = element_line(color = "black"),
        axis.text.x = element_text(color = "black"),
        axis.ticks.x = element_line(color = "black"),
        axis.ticks.length.x = unit(2, "mm")) +
  ggtitle("\nRisk ratio with 95% CI")


# patching the columns together
plot_stripes <- (labels_stripes | risk1_stripes | risk0_stripes | fp_stripes) +
  plot_layout(widths = c(1, 1, 1, 1.5))
Figure 2: Forest plot with stripes

Et voila! A forest plot which could in principle be presented as final.

The slightly more advanced plot

It might be desirable to include a few additional columns. Let us reload the data and tinker with some variables. Specifically, we want to have text variables combining numbers of events and at risk in each group, and also a text variable with risk ratios. For the sake of the example, we also want to cap the confidence intervals when they get below 0.5 or above 1.25:

rm(list = ls()[!(ls() %in% c("tsize", "colfun"))])

round2 <- function(x) format(round(x,digits = 2), nsmall = 2, scientific = FALSE)

dt <- fread("./data/SimpleFPdata.csv") |>
  mutate(
    # events and N at risk in the two groups
    en1 = case_when(is.na(events1) ~ "", .default = paste(events1, "/", n1)),
    en0 = case_when(is.na(events0) ~ "", .default = paste(events0, "/", n0)),
    
    # risk ratio with 95% CI
    risk_ratio = case_when(
      is.na(events0) ~ "",
      .default = paste0(round2(rr), " (", round2(lcl), " - ", round2(ucl), ")")
    ),
    
    y = n() - row_number(),
    indent = case_when(is.na(events1) | level == "Overall" ~ 0,
                       .default = 1),
    level = case_when(indent == 1 ~ paste("  ", level),
                      .default = level),
    boldface = case_when(indent == 0 ~ "bold",
                         .default = "plain"),
    
    # mark which confidence interval reach beyond the scale of the figure
    left_arrow = case_when(lcl < .5 ~ 1,
                           .default = 0),
    right_arrow = case_when(ucl > 1.25 ~ 1,
                            .default = 0),
    
    # truncate intervals
    lcl = case_when(left_arrow == 1 ~ .5,
                    .default = lcl),
    ucl = case_when(right_arrow == 1 ~ 1.25,
                    .default = ucl)
  )

stripesdt <- dt |>
  filter(y %% 2 == 0)

We recreate the columns we had already made, and further make columns with counts of events and individuals at risk, and risk ratios:

# labels
labels <- ggplot(dt, aes(x = 0, y = y, label = level, fontface = boldface)) +
  geom_rect(data = stripesdt,
            aes(xmin = -Inf, xmax = Inf, ymin = y - .5, ymax = y + .5),
            fill = "#f6f1ff") +
  geom_text(hjust = 0, size = tsize) +
  coord_cartesian(xlim = c(0, 1)) +
  # an empty title is added to make elements align when wrapping and patching below
  ggtitle("")

# columns for the intervention groups
eventsN1 <- colfun(en1, "Events / N")
risk1 <- colfun(risk1, "Risk (95% CI)")

# columns for the control groups
eventsN0 <- colfun(en0, "Events / N")
risk0 <- colfun(risk0, "Risk (95% CI)")

riskRatio <- colfun(risk_ratio, "") 

# the forest plot - with arrows (geom_segment) on capped intervals
fp <- ggplot(dt, aes(x = rr, xmin = lcl, xmax = ucl, y = y)) +
  geom_rect(data = stripesdt,
            aes(xmin = -Inf, xmax = Inf, ymin = y - .5, ymax = y + .5),
            fill = "#f6f1ff") +
  
  geom_vline(xintercept = 1, color = "grey", linetype = 2) +
  geom_pointrange(color = "#58508d", linewidth = 1.5) +
  
  # insert arrow at intervals truncated to the left
  geom_segment(data = subset(dt, left_arrow == 1),
               aes(xend = lcl, yend = y),
               arrow = arrow(length = unit(.25, "cm")),
               color = "#58508d",
               linewidth = 1.5) +
  
  # insert arrow at intervals truncated to the right
  geom_segment(data = subset(dt, right_arrow == 1),
               aes(xend = ucl, yend = y),
               arrow = arrow(length = unit(.25, "cm")),
               color = "#58508d",
               linewidth = 1.5) +
  
  # specify breaks on the x-axis
  scale_x_continuous(breaks = c(.5, .75, 1, 1.25),
                     limits = c(.5, 1.25)) +
  
  theme(axis.line.x = element_line(color = "black"),
        axis.text.x = element_text(color = "black"),
        axis.ticks.x = element_line(color = "black"),
        axis.ticks.length.x = unit(2, "mm"))

We now have the individual columns we want in our plot. However, to distinguish columns from the intervention- and control groups, we add an extra header spanning these columns using wrap_elements. Similarly, a header for the risk ratio text- and plot-columns is added. This messes up the alignment with the labels column, which is therefore wrapped and annotated by itself to restore alignment.

# labels are wrapped and annotated by themselves to restore alignment of rows
labels_wrap <- wrap_elements(
  (labels) +
    plot_annotation(title = "")
)

# common headers are added for the intervention group columns
eventsNrisk1 <- wrap_elements(
  (eventsN1 | risk1) +
    plot_annotation(title = "Intervention group")
)

# and the control group columns
eventsNrisk0 <- wrap_elements(
  (eventsN0 | risk0) +
    plot_annotation(title = "Control group")
)

# and finally for the risk ratio columns
riskRatiofp <- wrap_elements(
  (riskRatio | fp) +
    plot_annotation(title = "Risk ratio (95% CI)")
)

# everything is patched up together to get the final plot.
finalplot <- (labels_wrap | eventsNrisk1 | eventsNrisk0 | riskRatiofp) +
  plot_layout(widths = c(.4, 1, 1, 1.5)) +
  # some margin is added to the right to prevent tick values being cut
  theme(plot.margin = margin(r = .5, unit = "cm"))
Figure 3: Fully fledged forest plot

Note that the various parameters, i.e., tsize, base_size, relative widths, etc., generally need fine-tuning. The values used in this example are not universally valid.