Drawing multiple edges between two nodes with networkx

后端 未结 4 681
闹比i
闹比i 2020-12-05 20:31

I need to draw a directed graph with more than one edge (with different weights) between two nodes. That is, I have nodes A and B and edges (A,B) with length=2 and (B,A) wit

4条回答
  •  無奈伤痛
    2020-12-05 21:08

    Try the following:

    import networkx as nx
    import matplotlib.pyplot as plt
    G = nx.DiGraph() #or G = nx.MultiDiGraph()
    G.add_node('A')
    G.add_node('B')
    G.add_edge('A', 'B', length = 2)
    G.add_edge('B', 'A', length = 3)
    
    pos = nx.spring_layout(G)
    nx.draw(G, pos)
    edge_labels=dict([((u,v,),d['length'])
                 for u,v,d in G.edges(data=True)])
    nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels, label_pos=0.3, font_size=7)
    plt.show()
    

    This will return you this graph with two edges and the length shown on the edge:

    enter image description here

提交回复
热议问题