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...

  1. Let's import NumPy, NetworkX, and matplotlib:
    >>> import numpy as np
        import networkx as nx
        import matplotlib.pyplot as plt
        %matplotlib inline
  2. 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)]
  3. We instantiate a Graph object ...

Get IPython Interactive Computing and Visualization Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.