graphvizdot

Why does setting rankdir=LR order nodes top-to-bottom?


After several hacky/copy-paste graphviz diagrams, I'm making at attempt at understanding the dot language in earnest, and I have a very basic question. The following dot code:

digraph G
{
    subgraph cluster_obj
    {
        A [label="A"]
        B [label="B"]
    }
} 

...renders like this:

enter image description here

I understand, from the graphviz documentation, that rankdir=LR is only to be used at the graph level, and is meant for the purpose of arranging graphs left-to-right (I assume this means ordering subgraphs left-to-right.

Why, then, does adding rankdir=LR to the above simple graph result in the nodes within a subgraph being arranged top-to-bottom?

digraph G
{
    rankdir=LR
    subgraph cluster_obj
    {
        A [label="A"]
        B [label="B"]
    }
} 

enter image description here

I've been reading on graphviz/dot language from the graphviz.org official documentation, various Stack Overflow articles, and whatever hits web searches lead me to, but I haven't yet formed a comprehensive working knowledge of how to create and arrange diagrams to will. This question is inspired by this Stack Overflow answer, which seems to implicitly rely on rankdir=LR for the desired arrangements of its nodes 2 and 3 (which is crucial to the OP's question) -- but in that answer, as in the examples in this question, I don't see a pattern that reveals when and why nodes and subgraphs are arranged left-to-right vs. top-to-bottom.


Solution

  • Good question. Your assumption that rankdir's purpose is for ordering subgraphs left-to-right is incorrect. Rankdir specifies the ranking direction. (sorry for the circular definition, keep reading)
    The key concept here is rank - placing nodes into rows (or columns if rankdir=LR or RL). Except for a special case or two, ranking is performed based on edges. A head node is place on a greater rank that the tail node. Think about a diagram of a tree structure - the tail and head will be on different ranks.
    Your examples have no edges (perfectly legal), so all the nodes are placed on the same rank.
    For more in-depth info see https://graphviz.org/pdf/dotguide.pdf

    p.s. note that ranking only applies to the dot layout engine. The other Graphviz engines work based on other models.