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

查看:50
本文介绍了选择节点和边形成具有属性的 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天全站免登陆