Networkx: how to show node and edge attributes in a graph drawing

后端 未结 1 487
故里飘歌
故里飘歌 2020-12-24 02:55

I have a graph G with attribute \'state\' for nodes and edges. I want to draw the graph, all nodes labelled, and with the state marked outside the corresponding edge/node. <

相关标签:
1条回答
  • 2020-12-24 03:24

    It's not so pretty - but it works like this:

    from matplotlib import pyplot as plt
    import networkx as nx
    G = nx.Graph()
    G.add_edge(1,2)
    G.add_edge(2,3)
    for v in G.nodes():
        G.node[v]['state']='X'
    G.node[1]['state']='Y'
    G.node[2]['state']='Y'
    
    for n in G.edges_iter():
        G.edge[n[0]][n[1]]['state']='X'
    G.edge[2][3]['state']='Y'
    
    pos = nx.spring_layout(G)
    
    nx.draw(G, pos)
    node_labels = nx.get_node_attributes(G,'state')
    nx.draw_networkx_labels(G, pos, labels = node_labels)
    edge_labels = nx.get_edge_attributes(G,'state')
    nx.draw_networkx_edge_labels(G, pos, labels = edge_labels)
    plt.savefig('this.png')
    plt.show()
    

    enter image description here

    0 讨论(0)
提交回复
热议问题