Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change color for specific nodes in GGDAG

I am trying to reproduce the following graph in R with GGDAG. enter image description here

So far I am able to reproduce all nodes and arrows. However I do not know how to change the color of the "U" node and add the correspondent legend to the graph. Help is highly appreciated!See code for the uncolored DAG below.

library(ggplot2)
library(ggdag)

coord_dag <- list(
  x = c(P = 0, X = 2, D = 2, Z = 2, U = 4, M = 4, Y = 6),
  y = c(P = 2, X = 0, D = 2, Z = 6, U = 0, M = 3, Y = 2))

my_dag <- ggdag::dagify(X ~ P,
                         Z ~ P, 
                         D ~ X + Z, 
                         M ~ D + Z, 
                         U ~ X, 
                         Y ~ U + D + M + Z, 
                         coords = coord_dag, 
                         exposure = "D", 
                         outcome = "Y")  
          
  
ggdag::ggdag(my_dag) + 
  theme_dag()

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is a little tricky since there doesn’t seem to be the option directly within the function to label colours how you would like. Perhaps the easiest way would be to add an aesthetic mapping to the point layer:

p <- ggdag::ggdag(my_dag) + theme_dag()
p$layers[[3]]$mapping <- 
  aes(colour = c("Observed", "Unobserved")[as.numeric(name == "U") + 1])
p + scale_color_manual(values = c("black", "#cc2055")) +
  theme(legend.position = c(0.8, 0.8))

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading