This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.
In this recipe, we show how to create, manipulate and visualize graphs with NetworkX.
You can find the installation instructions of NetworkX on the official documentation. (http://networkx.github.io/documentation/latest/install.html)
In brief, you can just execute pip install networkx
. On Windows, you can also use Chris Gohlke's installer. (http://www.lfd.uci.edu/~gohlke/pythonlibs/#networkx)
import numpy as np
import networkx as nx
import matplotlib.pyplot as plt
%matplotlib inline
n = 10 # Number of nodes in the graph.
# Each node is connected to the two next nodes,
# in a circular fashion.
adj = [(i, (i+1)%n) for i in range(n)]
adj += [(i, (i+2)%n) for i in range(n)]
Graph
object here, giving the list of edges as argument.g = nx.Graph(adj)
print(g.nodes())
print(g.edges())
print(nx.adjacency_matrix(g))
draw_circular
function that simply positions nodes linearly on a circle.plt.figure(figsize=(4,4));
nx.draw_circular(g)
color
attribute to this node. In NetworkX, every node and edge comes with a Python dictionary containing arbitrary attributes. This feature is extremely useful in practice.g.add_node(n, color='#fcff00')
# We add an edge from every existing
# node to the new node.
for i in range(n):
g.add_edge(i, n)
plt.figure(figsize=(4,4));
# We define custom node positions on a circle
# except the last node which is at the center.
t = np.linspace(0., 2*np.pi, n)
pos = np.zeros((n+1, 2))
pos[:n,0] = np.cos(t)
pos[:n,1] = np.sin(t)
# A node's color is specified by its 'color'
# attribute, or a default color if this attribute
# doesn't exist.
color = [g.node[i].get('color', '#88b0f3')
for i in range(n+1)]
# We now draw the graph with matplotlib.
nx.draw_networkx(g, pos=pos, node_color=color)
plt.axis('off');
plt.figure(figsize=(4,4));
nx.draw_spectral(g, node_color=color)
plt.axis('off');
You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).
IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).