Manipulating and visualizing graphs with NetworkX
In this recipe, we will show how to create, manipulate, and visualize graphs with NetworkX.
Getting ready
NetworkX is installed by default in Anaconda. If needed, you can also install it manually with conda install networkx
.
How to do it...
- Let's import NumPy, NetworkX, and matplotlib:
>>> import numpy as np import networkx as nx import matplotlib.pyplot as plt %matplotlib inline
- There are many ways of creating a graph. Here, we create a list of edges (pairs of node indices):
>>> 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)]
- We instantiate a
Graph
object with our list of edges:>>> g = nx.Graph(adj)
- Let's check the list of nodes and edges of the graph, and its adjacency matrix:
>>> print(g.nodes()) [0, 1, 2, 3, 4, 5, 6, 7, 8...