#!/usr/bin/env python # coding: utf-8 # > This is one of the 100 recipes of the [IPython Cookbook](http://ipython-books.github.io/), the definitive guide to high-performance scientific computing and data science in Python. # # # 14.1. Manipulating and visualizing graphs with NetworkX # 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) # 1. Let's import NumPy, NetworkX, and matplotlib. # In[ ]: import numpy as np import networkx as nx import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # 2. There are many different ways to create a graph. Here, we create a list of edges. # In[ ]: 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)] # 3. We instantiate a `Graph` object here, giving the list of edges as argument. # In[ ]: g = nx.Graph(adj) # 4. Let's check the list of nodes and edges of the graph, and its adjacency matrix. # In[ ]: print(g.nodes()) # In[ ]: print(g.edges()) # In[ ]: print(nx.adjacency_matrix(g)) # 5. Now, we will display this graph. NetworkX comes with a variety of drawing functions. A graph being an abstract mathematical object only describing relations between items, there is no canonical way to display one. One needs to either specify the positions of the nodes explicitly, or an algorithm to compute an "interesting" layout. Here, we use the `draw_circular` function that simply positions nodes linearly on a circle. # In[ ]: plt.figure(figsize=(4,4)); nx.draw_circular(g) # 6. Graphs can be modified easily. Here, we add a new node connected to all existing nodes. We also specify a `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. # In[ ]: 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) # 7. Now, let's draw the modified graph again. This time, we specify the nodes' positions and colors explicitly. # In[ ]: 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'); # 8. Let's also use an automatic layout algorithm. # In[ ]: 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](http://ipython-books.github.io/), by [Cyrille Rossant](http://cyrille.rossant.net), Packt Publishing, 2014 (500 pages).