python中graphviz中的图节点位置

Graph node position in graphviz in python

我一直在寻找在python中的graphviz中指定图中节点位置的方法。 我在点中找到了一个子图的等级命令,这就是我想要的,但是我找不到在python中的graphviz中组合子图和等级的方法。 我也尝试强行设置节点位置,但也没有用。 我创建了一个简单的示例,说明了我想要实现的目标。

这是我的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from graphviz import Digraph

top_nodes = ['a', 'b', 'c']

other_nodes = ['d', 'e', 'f', 'g', 'm', 'n']

g = Digraph('test', format='png')

for n in top_nodes:
    g.node(str(n), color='red')

for n in other_nodes:
    g.node(str(n))

g.edge('a', 'd')
g.edge('d', 'g')
g.edge('g', 'm')
g.edge('m', 'n')
g.edge('b', 'e')
g.edge('b', 'f')
g.edge('e', 'n')
g.edge('c', 'f')

g.view()

这是输出:

graph

我希望红色节点("源")位于同一级别的图形顶部,其他节点的位置并不重要,只要保留层次结构即可。


我遇到了同样的问题,并发现使用子图可以解决该问题。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from graphviz import Digraph

top_nodes = ['a', 'b', 'c']

other_nodes = ['d', 'e', 'f', 'g', 'm', 'n']

g = Digraph('test', format='png')
s = Digraph('subgraph')
s.graph_attr.update(rank='min')

for n in top_nodes:
    s.node(str(n), color='red')

for n in other_nodes:
    g.node(str(n))

g.edge('a', 'd')
g.edge('d', 'g')
g.edge('g', 'm')
g.edge('m', 'n')
g.edge('b', 'e')
g.edge('b', 'f')
g.edge('e', 'n')
g.edge('c', 'f')

g.subgraph(s)

g.view()

影像输出


从代码开始,使用子图上下文就足够了,只需添加

1
2
3
with g.subgraph() as s:
    s.attr(rank = 'same')
    for n in top_nodes: s.node(n)

这似乎比显式声明一个子图并将其添加到原始图要容易。

顺便说一下,此解决方案生成的@DOT源与@RaHo答案中的ine完全相同。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
digraph test {
    a [color=red]
    b [color=red]
    c [color=red]
    d
    e
    f
    g
    m
    n
    a -> d
    d -> g
    g -> m
    m -> n
    b -> e
    b -> f
    e -> n
    c -> f
    {
        rank=same
        a
        b
        c
    }
}

尝试等级=相同的陈述

enter image description here

1
2
3
4
5
6
7
8
9
10
11
12
digraph G {
a b c d e f g m n
{rank = same; a; b; c;}
a->d
d->g
g->m
m->n
b->e
b->f
e->n
c->f
}