Search code examples
rgraphigraph

How to modify the layout of this graph?


I have created a graph object, but I would like to choose the layout myself. The layout I have in mind is such that first nodes Fs is placed at furthest left, then DCs and then CC and in the end Ws in the furthest right. We can also put DCs and CC beside each other. You can produce the graph by the following code:

graph_from_literal(F1--+DC1, F1--+DC2, F1--+DC3, F1--+CC, F1--+W1, F1--+W2, F1--+W3,
                   F2--+DC1, F2--+DC2, F2--+DC3, F2--+CC, F2--+W1, F2--+W2, F2--+W3, 
                   DC1--+CC, DC1--+W1, DC1--+W2, DC1--+W3, 
                   DC2--+CC, DC2--+W1, DC2--+W2, DC2--+W3, 
                   DC3--+CC, DC3--+W1, DC3--+W2, DC3--+W3, 
                   CC--+W1, CC--+W2, CC--+W3)

I tried the layout argument in plot function but the outcome is not what I have in mind. I would appreciate any help in advance.


Solution

  • If you want to customize your layered plot, we can try

    # assign x-coordiates of vertices in terms of their names by following the desired order, i.e., from left to right
    x_lo <- match(gsub("\\d", "", names(V(g))), c("F", "DC", "CC", "W"))
    
    # assign y-coordinates uniformly within the range [-5,5] (grouped by `x_lo`), or we can also use random values if you like
    y_lo <- ave(x_lo, x_lo, FUN = function(v) seq(-5, 5, length.out = length(v)))
    
    plot(g, layout = cbind(x_lo, y_lo))
    

    which gives

    enter image description here


    Another option might be using layout_with_sugiyama

    plot(g, layout = -layout_with_sugiyama(g)$layout[,2:1])
    

    and luckily we will obtain

    enter image description here