Graphs in Python for A Level Computer Science

Part 1 – Networkx Basics

networkx is a powerful python package that allows you to easily work with graphs in Python. Combining it with the matplotlib.pyplot package even makes it simple to draw graphs. This is very useful when learning or teaching about graphs for A Level Computer Science.

# Auto formatting - completely optional, requires installation.
%load_ext nb_black

Setup

import networkx as nx

G = nx.Graph()
print(G.nodes(), G.edges())
[] []

Nodes

G.add_node("A")
print(G.nodes())
['A']
G.add_nodes_from(["B", "C"])
print(G.nodes())
print("Number of nodes in graph: ", G.number_of_nodes())
['A', 'B', 'C']
Number of nodes in graph:  3

Edges

OK so now let’s look at how we add edges to our graph.

G.clear()  # First we clear the graph so we can start fresh
G.add_nodes_from(["A", "B", "C"])
G.add_edge("A", "B", weight=5)
G.add_edge("B", "C", weight=7)
G.add_edge("C", "A", weight=2)
print(G.nodes(), G.edges())
['A', 'B', 'C'] [('A', 'B'), ('A', 'C'), ('B', 'C')]

The Fun Part – Drawing Your Graph

Now we get to draw our graph. They say a picture is worth a thousand words and I agree. Python makes this super easy for us with just a couple of lines of code.

%matplotlib inline
import matplotlib.pyplot as plt

pos = nx.spring_layout(G)
weights = nx.get_edge_attributes(G, "weight")
nx.draw_networkx(G, pos, with_labels=True)
nx.draw_networkx_edge_labels(G, pos, edge_labels=weights)

plt.title("Basic Graphs with Networkx")
plt.gcf().canvas.set_window_title("")
plt.show()

I for one am pretty impressed by the networkx package. This article covers just the very basics, but already we have drawn a weighted graphs and learned how to add nodes and edges to an existing graph using networkx‘s powerful functionality.

Here’s the complete listing for this example, for your convenience:

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np


G = nx.Graph()  # Create empty graph

G.add_nodes_from(["A", "B", "C"])  # Add nodes

# Add edges
G.add_edge("A", "B", weight=5)
G.add_edge("B", "C", weight=7)
G.add_edge("C", "A", weight=2)

# Create drawing
pos = nx.spring_layout(G)  # List of positions of nodes
weights = nx.get_edge_attributes(G, "weight") # List of weights
nx.draw_networkx(G, pos, with_labels=True)
nx.draw_networkx_edge_labels(G, pos, edge_labels=weights)

plt.title("Basic Graphs with Networkx")
plt.gcf().canvas.set_window_title("")  # Hide window title

# Display Graph
plt.show()

Sharing is caring!

Leave a Reply

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