Python, pygraphviz, networkx

4 投票
1 回答
6125 浏览
提问于 2025-04-18 00:34

我用networkx构建了一个有向加权图,并且可以把它画出来,但即使这个图很小,边缘经常会交叉。我也试过用pygraphviz,但我无法添加标签。有人能帮我解决这个问题吗?

   edge_labels=dict([((u,v,),d['weight'])
              for u,v,d in DG.edges(data=True)])
   pylab.figure(1)
   pos=nx.spring_layout(DG)

   nx.draw(DG, pos)
   nx.draw_networkx_edge_labels(DG,pos,edge_labels=result,font_size=10)

   pylab.show()

如何把它转换成pygraphviz图并添加标签

1 个回答

6

Graphviz 是一个可以用来画图的工具,它会在边上显示 'label' 属性。下面是一个例子,展示了如何把边的权重设置为标签,如果这个权重存在的话。

import networkx as nx
import pygraphviz as pgv # need pygraphviz or pydot for nx.to_agraph()

G = nx.DiGraph()
G.add_edge(1,2,weight=7)
G.add_edge(2,3,weight=8)
G.add_edge(3,4,weight=1)
G.add_edge(4,1,weight=11)
G.add_edge(1,3)
G.add_edge(2,4)

for u,v,d in G.edges(data=True):
    d['label'] = d.get('weight','')

A = nx.to_agraph(G)
A.layout(prog='dot')
A.draw('test.png')

在这里输入图片描述

撰写回答