Graphs in Python using NetworkX

It is very easy to construct and use graphs in Python using the NetworkX software package. This Python language software package makes it easy to create, manipulate and understand the dynamics, functions, and structure of a complex network. In this Python tutorial, we will use this package to create a graph and show its basic implementation.

Tutorial: Graphs in Python using NetworkX

First of all, we need to install the package. Type the below command to install NetworkX in your system.

pip install networkx

Done that! Good. Now we’re ready to use it. First, create a nodeless graph as shown below. The graph created here is undirected.

import networkx

graph = networkx.Graph()

Creating a node

In order to create a node, use the add_node() function as shown below.

graph.add_node(1)

This will create a node with label 1 in the network. Let’s create more nodes.

graph.add_node(2)
graph.add_node(3)
graph.add_node(9)
graph.add_node(11)

We can also create a list of nodes as shown in the below code.

graph.add_nodes_from([6, 7, 8])

Once we are done executing all the above statements of codes, we will have a network of nodes 1, 2, 3, 6, 7, 9, 11 without any edges. Now we need to specify the edges in the graph.

Creating Edge

We can create an edge in the network using the given function here.

graph.add_edge(1, 2)

We can pass a list as an argument to add a list of edges in the network. See here.

graph.add_edges_from([(2, 3), (3, 7), (3, 9), (1, 9), (1, 11), (2, 6), (2, 8])

We can print the nodes and edges of the graph using nodes() and edges() functions. See the code given below.

print(graph.nodes)
print(graph.edges)

The above gives the output as:

[1, 2, 3, 9, 11, 6, 7, 8]
[(1, 2), (1, 9), (1, 11), (2, 3), (2, 6), (2, 8), (3, 7), (3, 9)]

Removing a node or an edge

We can remove a node or a list of nodes using the following functions.

graph.remove_node(6) #removes node 1 
graph.remove_nodes_from([7, 11]) # removes nodes 7, 11 passed as list

print(graph.nodes)
print(graph.edges)

Output:

[1, 2, 3, 9, 8]
[(1, 2), (1, 9), (2, 3), (2, 8), (3, 9)]

To remove an edge use remove_edge() function as done here.

graph.remove_edge(1, 9) #removes edge 1 to 9 

print(graph.nodes)
print(graph.edges)

Output:

[1, 2, 3, 9, 8]
[(1, 2), (2, 3), (2, 8), (3, 9)]

If you want to remove a list of edges, use remove_edges_from() function.

You can also draw the graph using matplotlib library. Do the following to draw it.

import matplotlib.pyplot as plt
networkx.draw(graph)
plt.show()

Thank you.

To read about the documentation on NetworkX: Read this.

Also read: Graph Plot of X and Y-Axis for given values as input in Python3

Leave a Reply

Your email address will not be published. Required fields are marked *