'Change color for specific nodes in GGDAG
I am trying to reproduce the following graph in R with GGDAG. 
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()
Solution 1:[1]
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))
Solution 2:[2]
You can use this code:
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()
Output:
Solution 3:[3]
To change the colour of your y node, add a new column to the tidy DAG and plot with the colour aesthetic:
Sample code:
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()
Plot:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Allan Cameron |
| Solution 2 | Quinten |
| Solution 3 | Rfanatic |



