knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.path = "man/figures/",
  out.width = "100%"
)
library(ggplot2)
set.seed(1542)

R-CMD-check CRAN status Lifecycle: maturing Codecov test coverage Total CRAN downloads

ggdag: An R Package for visualizing and analyzing causal directed acyclic graphs

Tidy, analyze, and plot causal directed acyclic graphs (DAGs). ggdag uses the powerful dagitty package to create and analyze structural causal models and plot them using ggplot2 and ggraph in a consistent and easy manner.

Installation

You can install ggdag with:

install.packages("ggdag")

Or you can install the development version from GitHub with:

# install.packages("devtools")
devtools::install_github("r-causal/ggdag")

Example

ggdag makes it easy to use dagitty in the context of the tidyverse. You can directly tidy dagitty objects or use convenience functions to create DAGs using a more R-like syntax:

library(ggdag)
library(ggplot2)

#  example from the dagitty package
dag <- dagitty::dagitty("dag {
    y <- x <- z1 <- v -> z2 -> y
    z1 <- w1 <-> w2 -> z2
    x <- w1 -> y
    x <- w2 -> y
    x [exposure]
    y [outcome]
  }")

tidy_dag <- tidy_dagitty(dag)

tidy_dag

#  using more R-like syntax to create the same DAG
tidy_ggdag <- dagify(
  y ~ x + z2 + w2 + w1,
  x ~ z1 + w1 + w2,
  z1 ~ w1 + v,
  z2 ~ w2 + v,
  w1 ~ ~w2, # bidirected path
  exposure = "x",
  outcome = "y"
) %>%
  tidy_dagitty()

tidy_ggdag

ggdag also provides functionality for analyzing DAGs and plotting them in ggplot2:

ggdag(tidy_ggdag) +
  theme_dag()
ggdag_adjustment_set(tidy_ggdag, node_size = 14) +
  theme(legend.position = "bottom")

As well as geoms and other functions for plotting them directly in ggplot2:

dagify(m ~ x + y) %>%
  tidy_dagitty() %>%
  node_dconnected("x", "y", controlling_for = "m") %>%
  ggplot(aes(
    x = x,
    y = y,
    xend = xend,
    yend = yend,
    shape = adjusted,
    col = d_relationship
  )) +
  geom_dag_edges(end_cap = ggraph::circle(10, "mm")) +
  geom_dag_collider_edges() +
  geom_dag_point() +
  geom_dag_text(col = "white") +
  theme_dag() +
  scale_adjusted() +
  expand_plot(expand_y = expansion(c(0.2, 0.2))) +
  scale_color_viridis_d(
    name = "d-relationship",
    na.value = "grey85",
    begin = .35
  )

And common structures of bias:

ggdag_equivalent_dags(confounder_triangle())

ggdag_butterfly_bias(edge_type = "diagonal")


malcolmbarrett/ggdag documentation built on March 8, 2024, 5:49 p.m.