选择具有属性的networkx图的节点和边 [英] Select nodes and edges form networkx graph with attributes

查看:171
本文介绍了选择具有属性的networkx图的节点和边的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始在networkx中制作图,我想及时了解图的演变:它的变化方式,在指定的时间t图中有哪些节点/边.

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.

这是我的代码:

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.

所以,我的问题是:

如何设计基于时间的过滤器,该过滤器将仅在时间t提取我的图G图上的相关节点/边,例如"2014年7月".完成后,如何使用matplotlib更新图?

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'. When it is done, how do I update the graph with matplotlib?

预先感谢您的帮助

推荐答案

您可以使用G.nodes()方法通过具有列表理解的条件选择节点:

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)

出局:[1, 2]

要选择边缘,请使用G.edges_iterG.edges方法:

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)

出局:[(1, 2)]

要绘制选定的节点,请调用G.subgraph()

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()

这篇关于选择具有属性的networkx图的节点和边的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆