Select nodes and edges form networkx graph with attributes

前端 未结 1 1554
误落风尘
误落风尘 2021-01-03 03:00

I\'ve just started doing graphs in networkx and I want to follow the evolution of a graph in time: how it changed, what nodes/edges are in the graph at a specified time t.

相关标签:
1条回答
  • 2021-01-03 03:51

    You may select nodes by conditions with list comprehension with G.nodes() method:

    selected_nodes = [n for n,v in G.nodes(data=True) if v['since'] == 'December 2008']  
    print (selected_nodes)
    

    Out: [1, 2]

    To select edges use G.edges_iter or G.edges methods:

    selected_edges = [(u,v) for u,v,e in G.edges(data=True) if e['since'] == 'December 2008']
    print (selected_edges)
    

    Out: [(1, 2)]

    To plot selected nodes call G.subgraph()

    H = G.subgraph(selected_nodes)
    nx.draw(H,with_labels=True,node_size=3000)
    

    To plot selected edges with attributes you may construct new graph:

    H = nx.Graph(((u, v, e) for u,v,e in G.edges_iter(data=True) if e['since'] == 'December 2008'))
    nx.draw(H,with_labels=True,node_size=3000)
    plt.show()
    

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