NetworkX Basics

Module 5: Complex Networks

Toolkit page

This page is self-study material for Session 23. Work through it before the network labs.

A graph models pairwise relations between objects. It consists of nodes (also called vertices) and edges (also called links) that connect pairs of nodes (Newman 2018).

This page shows how to build graphs with the networkx library (Hagberg, Schult, and Swart 2008). NetworkX is a Python package for the creation, manipulation and study of the structure, dynamics and functions of complex networks. The examples follow A First Course in Network Science (Menczer, Fortunato, and Davis 2020); see the book’s GitHub repository. The folder references/networkx_indiana of this repository has the matching notebooks. You will learn to:

Use notebooks for this module

Follow the network pages in a Jupyter notebook rather than a standalone script. You run one cell at a time, keep figures and notes next to the code, and debug simulations and parameter sweeps faster.

First, import the library:

If you get a ModuleNotFoundError for networkx, you may need to install it first.

If you are working on Google Colab, you can run:

!pip install networkx

If you are working in a local Python environment, use conda or run:

pip install networkx

Now initialize an empty graph:

G = nx.Graph()

print(G)
Graph with 0 nodes and 0 edges

G is now an empty undirected graph. The next sections add nodes and edges to it.

Nodes (Vertices)

Nodes represent the entities in a graph. They can be anything: people in a social network, airports in a flight network, or web pages in the internet.

To add nodes, use the add_node(<id>) method. The <id> can be any hashable Python object. You can see the list of nodes in the graph using the nodes() method.

# Add three nodes to the graph
G.add_node("Spain")
G.add_node("Portugal")
G.add_node("France")

# Show the nodes in the graph
print(G.nodes())
['Spain', 'Portugal', 'France']

In Python, a hashable object is an object that has a hash value that remains constant during its lifetime. This means that the object can be used as a key in a dictionary or as an element in a set. Examples of hashable objects include integers, strings, and tuples (as long as they contain only hashable types). Lists and dictionaries are not hashable because they are mutable (their contents can change).

Node Attributes

Each node can have attributes that provide additional information about it. For example, in a social network, a node might represent a person and have attributes like name, age, or location.

NetworkX stores attributes on nodes. Think of G.nodes as a dictionary where the keys are the node IDs and the values are dictionaries of attributes. You can add attributes to a node by accessing it through G.nodes[<id>] and assigning values to the attributes.

For example, add a “population” attribute to the country nodes:

# Add population attribute to the nodes
G.nodes["Spain"]["population"] = 47_000_000
G.nodes["Portugal"]["population"] = 10_000_000
G.nodes["France"]["population"] = 67_000_000

# Show the nodes with their attributes
population = nx.get_node_attributes(G, 'population')
for node, pop in population.items():
    print(f"{node}: {pop} inhabitants")
Spain: 47000000 inhabitants
Portugal: 10000000 inhabitants
France: 67000000 inhabitants

Using get_node_attributes(G, 'population'), you can retrieve the population attribute for all nodes in the graph as a dictionary.

If you are including a new node and want to add attributes at the same time, you can use the add_node() method with keyword arguments. For example:

# Add a new node with attributes
G.add_node("Italy", population=60_000_000)

# Show the nodes with their attributes
population = nx.get_node_attributes(G, 'population')
for node, pop in population.items():
    print(f"{node}: {pop} inhabitants")
Spain: 47000000 inhabitants
Portugal: 10000000 inhabitants
France: 67000000 inhabitants
Italy: 60000000 inhabitants

What’s Next?

The next page adds edges and edge attributes to this graph.

Edges and Weights

References

Hagberg, Aric A., Daniel A. Schult, and Pieter J. Swart. 2008. “Exploring Network Structure, Dynamics, and Function Using NetworkX.” In Proceedings of the 7th Python in Science Conference (SciPy 2008), 11–15.
Menczer, Filippo, Santo Fortunato, and Clayton A. Davis. 2020. A First Course in Network Science. Cambridge University Press.
Newman, Mark. 2018. Networks. 2nd ed. Oxford University Press.