[英]Select nodes and edges form networkx graph with attributes
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. 我刚开始在networkx中做图表,我想及时跟踪图形的演变:它是如何变化的,图形中指定时间t的节点/边缘是什么。
Here is my code: 这是我的代码:
import networkx as nx
import matplotlib.pyplot as plt
G=nx.Graph()
G.add_node(1,id=1000,since='December 2008')
G.add_node(2,id=2000,since='December 2008')
G.add_node(3,id=3000,since='January 2010')
G.add_node(4,id=2000,since='December 2016')
G.add_edge(1,2,since='December 2008')
G.add_edge(1,3,since='February 2010')
G.add_edge(2,3,since='March 2014')
G.add_edge(2,4,since='April 2017')
nx.draw_spectral(G,with_labels=True,node_size=3000)
plt.show()
This shows the graph with all the nodes and edges. 这显示了包含所有节点和边的图。
So, my question is: 所以,我的问题是:
How to design a time-based filter that will extract only the relevant nodes/edges on my graph G graph at time t, say for example 'July 2014'. 如何设计一个基于时间的过滤器,它将在时间t仅提取我的图G图上的相关节点/边,例如'2014年7月'。 When it is done, how do I update the graph with matplotlib?
完成后,如何使用matplotlib更新图形?
Thank you in advance for your help 预先感谢您的帮助
You may select nodes by conditions with list comprehension with G.nodes()
method: 您可以通过使用
G.nodes()
方法的列表理解条件选择节点:
selected_nodes = [n for n,v in G.nodes(data=True) if v['since'] == 'December 2008']
print (selected_nodes)
Out: [1, 2]
出:
[1, 2]
To select edges use G.edges_iter
or G.edges
methods: 要选择边缘,请使用
G.edges_iter
或G.edges
方法:
selected_edges = [(u,v) for u,v,e in G.edges(data=True) if e['since'] == 'December 2008']
print (selected_edges)
Out: [(1, 2)]
出:
[(1, 2)]
To plot selected nodes call G.subgraph()
要绘制所选节点,请调用
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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.