Ben
Ben

Reputation: 1486

How do you change node colours for ggdag plots in R?

The ggdag package allows you to create and plot DAGs in R. Here is an example:

#Load libraries
library(ggdag)
library(ggplot2)

#Create and print a DAG
DAG <- dagify(y ~ x, x ~ a, a ~ y)
ggdag(DAG)

enter image description here

I would like to adjust this plot to colour some of the nodes (of my choice) in a different colour. For example, suppose I want to colour node y in red. How do I do this?

Upvotes: 0

Views: 1699

Answers (1)

Robert Hawlik
Robert Hawlik

Reputation: 472

You get the most flexibility out of {ggdag} by plotting directly with {ggplot2}. To colour your y node in another colour, add a new column to the tidy DAG and plot with the colour aesthetic:

#Load libraries
library(ggdag)
library(ggplot2)

DAG <- dagify(y ~ x, x ~ a, a ~ y) %>% 
  tidy_dagitty() %>% 
  dplyr::mutate(colour = ifelse(name == "y", "Colour 1", "Colour 2"))

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

enter image description here

Upvotes: 3

Related Questions