使用 python 字典和图在 Graphviz 中标记节点

Labelling nodes in Graphviz using python dictionary and agraph

我正在尝试使用 Python 的 networkx 创建一个显示自循环的有向图图像。 Networkx 没有显示它们,但其他在线论坛建议将 networkx 与 graphviz 连接起来。这是我在 Python 中为五节点定向网络输入的内容。

 # Import packages
 import networkx as nx
 import numpy as npy
 from networkx.drawing.nx_agraph import to_agraph

 #Non-symmetric adjacency matrix with self-loop at 1.
 A=npy.matrix([[1,1,1,0,0],[1,0,1,0,0],[1,1,0,1,1],[0,0,1,0,1], 
 [0,0,1,1,0]])
 #Create directed graph
 G=nx.DiGraph(A)

 #add graphviz layout options (as per advice at
 #

 G.graph['edge'] = {'arrowsize': '0.8', 'splines': 
 'curved','shape':'circle'}
 G.graph['graph'] = {'scale': '3'}
 G.graph['node']={'shape':circle','fillcolor':'red'} 
 D = to_agraph(G) 
 D.layout('dot')
 D.draw('multi.png')  

一切正常。但是,我想使用存储在 Python 字典中的标签作为 标签={0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}

我不确定如何在 graphviz 布局选项中添加它。显然,这是一个简单的图表,但我的字典标签通常更大。

您可以通过在将 NetworkX 图转换为 Graphviz AGraph 之前为每个节点设置一个 'label' 属性来实现:

...
labels={0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}
nx.set_node_attributes(G, {k:{'label':labels[k]} for k in labels.keys()})
D = to_agraph(G)

结果为: