3

Using this reproducable example from another question. How do I label / colour the center node on which the local neighborhood graph is based. (In this case 'x')

library(tidygraph)
library(ggraph)


# Example
net <- tibble::tibble(A = letters[1:6],
                      B = rep(c("x", "y"), each = 3)) %>% 
  tidygraph::as_tbl_graph()

net %>%
  tidygraph::convert(to_local_neighborhood,
                     node = which(.N()$name == "x"),
                     order = 1,
                     mode = "all") %>%
  ggraph(layout = "nicely") +
  geom_edge_link() +
  geom_node_point(size = 10, fill = "white", shape = 21) +
  geom_node_text(aes(label = name)) +
  theme_graph()

What I get:

enter image description here

What I want:

enter image description here

I have the feeling there should be some kind of conditional fill for geom_node_point but I don't know if this is possible...

Nina van Bruggen
  • 393
  • 2
  • 13

1 Answers1

2

You can do:

net %>%
  tidygraph::convert(to_local_neighborhood,
                     node = which(.N()$name == 'x'),
                     order = 1,
                     mode = "all") %>%
  mutate(root = ifelse(node_is_center(), 'red', 'white')) %>%
  ggraph(layout = "nicely") +
  geom_edge_link() +
  geom_node_point(size = 10, aes(fill = root), shape = 21) +
  geom_node_text(aes(label = name)) +
  scale_fill_identity() +
  theme_graph()

enter image description here

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87
  • Thank you for your answer. What I was actually looking for is some way to automatically color the center node. So if I change the center node to 'a', I don't have to change the scale_fill_manual as well. But maybe that option just doesn't exist.. – Nina van Bruggen Mar 28 '22 at 09:48
  • 1
    @NinavanBruggen actually, there is the `node_is_center()` function, so this is possible - see my update. – Allan Cameron Mar 28 '22 at 10:21