Search code examples
graphviz

Vertically align Nodes inside a cluster using Graphviz


EDIT

After doing a trial and error, I found that there is no straight answer to it (please feel free to add if there is one).

What I did finally was, to remove "rank=same" when the nodes are expected to be shown one-above-other and keep when they are to be displayed horizontally.

So, in my example below I removed "rank=same" from "cluster_1".

Do let me know in case there are other methods to achieve this.


Currently, I'm trying to create a SVG using Graphviz in Python. The dot string is able to create the required graph. But when I put all nodes in a specific cluster, they are always aligned horizontally. Example - If I have a Node A which is connected to B & C at the same level (in a cluster say cluster_0) and connected nodes D, E and F in another cluster, B is also connected to E, it creates something like below

A - B - C    
    | 
D - E - F

What I was looking for is, if I can create something like below

A - B - C    
    | 
D - E 
    |
    F

Also, when the last Node of fist cluster is connected to fist node of next cluster, it shifts the second cluster to right..

Below is my sample code.

digraph digram {
ordering=out;

center=1;
splines = ortho;
node [shape=box];
 nd_1 [label="A"];
 nd_2 [label="B"];
 nd_3 [label="C"];
 nd_4 [label="D"];
 nd_5 [label="E"];
 nd_6 [label="F"];
 nd_7 [label="G"];
 nd_8 [label="H"];

  subgraph cluster_0{
    label ="Cluster 0";
    { rank=same nd_1 nd_2 nd_3}
    nd_1 -> nd_2 nd_2 -> nd_3
  }
    subgraph cluster_1{
    label ="Cluster 1";
    { rank=same nd_4 nd_5 nd_6 nd_7 nd_8}
    nd_4 -> nd_5 nd_5 -> nd_6 nd_6 -> nd_7 nd_7 -> nd_8
  }
  nd_3-> nd_5
}

Solution

  • You are forcing nd_4, nd_5, nd_6, nd_7 and nd_8 to be on same rank.

    To achieve the desired graph, don't set nd_4 and nd_5 on the same rank as nd_6, nd_7 and nd_8.

    digraph digram {
    
    splines = ortho;
    node [shape=box];
     nd_1 [label="A"];
     nd_2 [label="B"];
     nd_3 [label="C"];
     nd_4 [label="D"];
     nd_5 [label="E"];
     nd_6 [label="F"];
     nd_7 [label="G"];
     nd_8 [label="H"];
    
      subgraph cluster_0{
        label ="Cluster 0";
        { rank=same nd_1 nd_2 nd_3}
        nd_1 -> nd_2 nd_2 -> nd_3
      }
        subgraph cluster_1{
        label ="Cluster 1";
        { rank=same nd_4 nd_5}
        nd_4 -> nd_5 nd_5 -> nd_6 nd_6 -> nd_7 nd_7 -> nd_8
      }
      nd_2-> nd_5
    }
    

    preview graph