EllipticalInitial
EllipticalInitial

Reputation: 1270

How to keep nodes on the same rank using Python and Graphviz?

So apparently the way to keep certain nodes in GraphViz on the same level is to use something like:

{rank = same; n5; n6; n7; n8;}

However, I'm trying to automate all of this inside Python using: https://graphviz.readthedocs.io/en/stable/index.html

And while I can figure out how to add basic attributed to the graph (such as a label), I cannot figure out how to specify that certain nodes need to be in the same rank from inside Python! I know that this can be done, but I cannot figure out the syntax. If you see here: http://graphviz.readthedocs.io/en/stable/manual.html#attributes

It even says that you can use "rank=same." So I know that it can be done, but I just cannot figure out how to do it.

Can somebody please provide a working example in Python where they specify that certain nodes are on the same rank (where they normally wouldn't be if the specification hadn't been made)? Thank you very much

Upvotes: 5

Views: 6600

Answers (1)

Craig
Craig

Reputation: 4855

You can create a subgraph that includes the nodes you want on the same rank and set rank='same' as an attribute of the subgraph. Here's an example with three nodes:

from graphviz import Graph

g = Graph('parent')

c = Graph('child')
c.attr(rank='same')
c.node('A')
c.node('B')
c.node('C')
c.edge('A', 'B') #without rank='same', B will be below A

g.subgraph(c)

print(g.source)

This produces the dot source

graph parent {
    subgraph child {
        rank=same
        A
        B
        C
        A -- B
    }
}

and is rendered by dot as

Three nodes rendered on same rank

You can also include nodes that have already been defined defined in the main graph, so you could create all of your node, with their attributes and edges defined and then create a subgraph for each group of nodes you want on the same rank.

As an example, you will get the same graph with:

g = Graph('parent')

g.node('A')
g.node('B')
g.node('C')
g.edge('A', 'B') #without rank='same', B will be below A

c = Graph('child')
c.attr(rank='same')
c.node('A')
c.node('B')
c.node('C')

g.subgraph(c)

Upvotes: 6

Related Questions