Search code examples
rigraphggraph

ggraph: Vertex position according to attribute


Suppose I have an igraph graph like the following:

library(ggraph)
library(igraph)

vertices <- data.frame(name = LETTERS[1:6],
                       time = c(0, 9, 9, 10, 10, 10))
edges <- data.frame(from = c("A", "B", "B", "A", "C", "C"),
                    to =   c("B", "D", "E", "C", "E", "F"))
graph <- graph_from_data_frame(edges, 
                               directed = TRUE, 
                               vertices = vertices)

For present purposes, the graph will always be a tree or a DAG, and I would like to use ggraph to plot the graph in a tree-like layout. My question is: How to plot this graph with the time vertex attribute for y-values?

I can set aes(y = time) in geom_node_point to correctly position the nodes, but the edges do not follow along:

ggraph(graph, layout = "tree") + 
  geom_node_point(aes(y = time)) +
  geom_edge_link() +
  theme_bw()

Created on 2019-11-17 by the reprex package (v0.3.0)

Setting the y or yend aesthetic to time in geom_edge_link throws an error.

I am new to ggraph, so I'm stuck on how to proceed with this problem.


Solution

  • It is not pretty, but you can achieve this by creating your own layout.

    LO = layout_as_tree(graph)
    LO[, 2] = V(graph)$time
    
    ggraph(graph, layout = LO) + 
      geom_node_point() +
      geom_edge_link() +
      theme_bw()
    

    graph with time as y-axis in layout