Search code examples
rtidyverseggraphtidygraph

How to hide unconnected nodes in ggraph


Given the following example code,

library(tidyverse)
library(tidygraph)
library(ggraph)

reprex <- tibble(to = 1:10,
                  from = c(2:10, 1),
                  facet = rep(1:2, each = 5)) %>%
    as_tbl_graph()

reprex_plot <- reprex %>%
    ggraph() +
    geom_node_point() +
    geom_edge_link()

reprex_plot + facet_edges(~ facet)

how can I hide the nodes that don't have an edge going into or coming out of the node?


Solution

  • library(tidyverse)
    library(tidygraph)
    library(ggraph)
    
    reprex2 <- tibble(to = 1:10,
                     from = c(2:10, 1)) %>%
        as_tbl_graph() %>%
        activate(nodes) %>%
        mutate(facet = rep(1:2, each = 5))
    
    reprex_plot <- reprex2 %>%
        ggraph() +
        geom_node_point() +
        geom_edge_link()  +
        geom_node_label(aes(label = name)) +
        theme_graph() + 
        facet_nodes(~ facet)
    
    reprex_plot
    

    I can empathize with your approach, but difficulty arises with the intelligence of tidygraph's as_tbl_graph(). You are passing it essentially an edge list where facet is a variable that only applies to the edges. You can verify this by doing reprex %>% activate(nodes) %>% as_tibble() to see that the facet column has no association with the nodes.

    My solution is to construct the facet column explicitly on the nodes then use facet_nodes() which is the converse of facet_edges() in that

    Edges are drawn if their terminal nodes are both present in a panel.