Search code examples
graphvizdot

Graphviz - define the order of the clusters


I'm generating clustered nodes in graphviz/dot. Simplified example:

digraph G {
    rankdir=LR

    n2a->n3
    n1->n2b
    n2b->n2a
    n2b->n3
    n3->n1

    subgraph cluster_1 { label="cluster_1" n1 }
    subgraph cluster_2 { label="cluster_2" n2a n2b }
    subgraph cluster_3 { label="cluster_3" n3 }
}

I want to force dot to always put the clusters in ascending order from right to left (cluster 1 in the left, next is cluster 2 etc.), but to arrange the nodes inside each cluster as dot dictates automatically.

I tried to play with clusterrank, rank, newrank, constraint=false and couldn't manage to make it happen. How can it be done?


Solution

  • You can "force" this to happen by adding edges to establish rank of every node in every cluster. Every node in cluster_1 has a lesser rank than every node in cluster_2, etc. Like so:

    digraph G {
        rankdir=LR
    
        n2a->n3
        n1->n2b
        n2b->n2a
        n2b->n3
        n3->n1
    
        subgraph cluster_1 { label="cluster_1" n1 }
        subgraph cluster_2 { label="cluster_2" n2a n2b }
        subgraph cluster_3 { label="cluster_3" n3 }
        // simple-minded solution - force clusters based on (added) rank
        edge [style=invis]
        {n1} -> {n2a n2b} -> {n3}
    }
    

    Giving: enter image description here