Iaroslav Domin Iaroslav Domin - 10 months ago 69
R Question

R, igraph: ordered layout


be an
object. For example,
g <- make_graph(~A-C-B, C-D, E-D-F)
. And let us set up a vertex attribute called

V(g)[c("A", "B")]$level <- 1
V(g)[c("C")]$level <- 2
V(g)[c("D")]$level <- 3
V(g)[c("E", "F")]$level <- 4

Are there any tools in
to build a layout for
such that it respects
in a meaning that a vertex with less
is always placed to the left and vertices with same level have the same (or close) abscissa.

So, for the given graph I'd like to see a picture like this:enter image description here

Answer Source

Since a layout in igraph is just a matrix of {x,y} coordinates, you can set the x-coordinates equal to your levels.

g <- make_graph(~A-C-B, C-D, E-D-F)
V(g)$level <- c(1,2,1,3,4,4)
l <- matrix(c(V(g)$level,1,2,3,2,3,1),nrow=length(V(g)$level),ncol=2)
plot(g, layout=l)

enter image description here

I just did the y-axis by hand, but you can construct it as you see fit.

Using Sugiyama layout

Sugiyama layout works by adding layers. There are a lot of options with the layout, but, basically, it tries to create a hierarchical representation of the graph.

l <- layout_with_sugiyama(g, layers = -V(g)$level)$layout
#note the "-", this ensures that the smaller level values get small x coordinates