How to use math symbols with ggdag
[This article was first published on Shige's Research Blog, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
The wonderful package ggdag can easily make DAG like this:Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
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.
To leave a comment for the author, please follow the link and comment on their blog: Shige's Research Blog.
R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.