Tuesday, October 01, 2019

How to use math symbols with ggdag

The wonderful package ggdag can easily make DAG like this:


However, what we really want to include in publications is something like this:


The second one can include subscript and superscript, among many others. After some tweaking, I found a solution, not perfect but usable for now.

-----------------------------------------------------------------
library(dagitty)
library(ggdag)
library(ggraph)
library(cowplot)
library(dplyr)

```{r, echo=FALSE}
dag <- dagify(Y1 ~ X + Z1 + Z0 + U + P,
              Y0 ~ Z0 + U,
              X ~ Y0 + Z1 + Z0 + P,
              Z1 ~ Z0,
              P ~ Y0 + Z1 + Z0,
              exposure = "X",
              outcome = "Y1")


dag %>% 
  tidy_dagitty(layout = "auto", seed = 12345) %>%
  arrange(name) %>% 
  ggplot(aes(x = x, y = y, xend = xend, yend = yend)) +
  geom_dag_point() +
  geom_dag_edges() +
  geom_dag_text(parse = TRUE, label = c("P", "U", "X", expression(Y[0]), expression(Y[1]), expression(Z[0]), expression(Z[1]))) +
  theme_dag()
-----------------------------------------------------------------

Here the trick is to sort the tidy version of the DAG data by "name", then we can assign labels by the order of the name of the nodes. I hope a more automated approach can be developed in the future.

By the way, with the package latex2exp, it is straightforward to use LaTeX instead of plotmath commands.

No comments:

Counter