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

时间:2018-03-25 20:01:01

标签: python python-3.x graph syntax 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

1 个答案:

答案 0 :(得分:0)

您可以创建一个子图,其中包含您想要在同一等级上的节点,并将rank='same'设置为子图的属性。这是一个有三个节点的例子:

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)

这会产生点源

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

并由dot呈现为

Three nodes rendered on same rank

您还可以包含已在主图中定义的已定义的节点,这样您就可以创建所有节点,并定义其属性和边,然后为相同等级的每个节点组创建一个子图

例如,您将获得与以下相同的图表:

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)