Add edge-weights to plot output in networkx

前端 未结 2 923
醉酒成梦
醉酒成梦 2020-12-13 04:58

I am doing some graph theory in python using the networkx package. I would like to add the weights of the edges of my graph to the plot output. How can I do this?

相关标签:
2条回答
  • 2020-12-13 05:13

    I like to do it like this:

    import matplotlib.pyplot as plt
    pos=nx.spring_layout(G) # pos = nx.nx_agraph.graphviz_layout(G)
    nx.draw_networkx(G,pos)
    labels = nx.get_edge_attributes(G,'weight')
    nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
    
    0 讨论(0)
  • 2020-12-13 05:14

    You'll have to call nx.draw_networkx_edge_labels(), which will allow you to... draw networkX edge labels :)

    EDIT: full modified source

    #!/usr/bin/python
    import networkx as nx
    import matplotlib.pyplot as plt
    
    G=nx.Graph()
    i=1
    G.add_node(i,pos=(i,i))
    G.add_node(2,pos=(2,2))
    G.add_node(3,pos=(1,0))
    G.add_edge(1,2,weight=0.5)
    G.add_edge(1,3,weight=9.8)
    pos=nx.get_node_attributes(G,'pos')
    nx.draw(G,pos)
    labels = nx.get_edge_attributes(G,'weight')
    nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)
    plt.savefig(<wherever>)
    
    0 讨论(0)
提交回复
热议问题