pythonnetworkxpygraphviz

Python, pygraphviz, networkx


I built a directed weighted graph using networkx and I can draw it, but it has very often crossed edges even if the graph is very small. I used pygraphviz also, but I was unable to add labels. Can someone help me with that ?

   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()

How to convert it to pygraphviz graph and add labels to it


Solution

  • Graphviz draws the 'label' attribute on edges. Here is an example of setting the label attribute to the edge weight if it exists.

    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.nx_agraph.to_agraph(G)
    A.layout(prog='dot')
    A.draw('test.png')
    

    enter image description here