更改 GGDAG 中特定节点的颜色

Change color for specific nodes in GGDAG

我正在尝试使用 GGDAG 在 R 中重现下图。

到目前为止,我能够重现所有节点和箭头。但是我不知道如何更改“U”节点的颜色并将相应的图例添加到图中。非常感谢您的帮助!请参阅下面未着色的 DAG 的代码。

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()

这有点棘手,因为似乎没有直接在函数内的选项来标记您想要的颜色。也许最简单的方法是向点图层添加美学映射:

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))

要更改 y 节点的颜色,请将新列添加到整洁的 DAG 并使用颜色美学绘图:

示例代码:

library(ggplot2)
library(ggdag)
library(dplyr)

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")  %>% 

         tidy_dagitty() %>% 
  dplyr::mutate(colour = ifelse(name == "U", "Unobserved", "Observed"))
         
      
ggdag::ggdag(my_dag) + 
  geom_dag_point(aes(colour = colour)) +
  geom_dag_edges() +
  geom_dag_text() +
  theme_dag()

剧情:

您可以使用此代码:

library(ggplot2)
library(ggdag)
library(dplyr)

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") %>%
  tidy_dagitty() %>%
  mutate(colour = ifelse(name == "U", "Unobserved", "Observed"))

my_dag %>%
  ggplot(aes(x = x, y = y, xend = xend, yend = yend)) +
  geom_dag_point(aes(colour = colour)) +
  geom_dag_edges() +
  geom_dag_text() +
  theme_dag()

输出: