Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

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

Thank you in advance for your help

like image 814
jezzy Avatar asked Jul 27 '17 12:07

jezzy


1 Answers

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(data=True) if e['since'] == 'December 2008'))
nx.draw(H,with_labels=True,node_size=3000)
plt.show()

enter image description here

like image 199
Serenity Avatar answered Sep 19 '22 22:09

Serenity