Graphs Using NetworkX

Posted by Beetle B. on Mon 28 July 2014

NetworkX is a Python library for handling graphs.

In [1]:
%matplotlib inline
In [14]:
import networkx as nx
import pylab as plt
In [3]:
G = nx.Graph()
In [4]:
G.add_nodes_from(range(4))
In [5]:
G.add_edges_from([(1, 2), (1, 4)])
G.add_edges_from([(3, 1)])
G.add_edges_from([(2, 3)])
In [15]:
nx.draw(G, with_labels=True, alpha=0.6)
plt.savefig("sample_graph")
In [17]:
G.degree()
Out[17]:
{0: 0, 1: 3, 2: 2, 3: 2, 4: 1}
In [19]:
G.adjacency_list()
Out[19]:
[[], [2, 3, 4], [1, 3], [1, 2], [1]]
In [23]:
G.neighbors(2)
Out[23]:
[1, 3]
In [25]:
list(nx.connected_components(G))
Out[25]:
[[0], [1, 2, 3, 4]]
In [27]:
nx.shortest_path_length(G, 2)
Out[27]:
{1: 1, 2: 0, 3: 1, 4: 2}