python-igraph Manual

For using igraph from Python

Minimum Spanning Trees

Minimum Spanning Trees

This example shows how to generate a minimum spanning tree from an input graph using spanning_tree(). If you only need a regular spanning tree, check out Spanning Trees.

We start by generating a grid graph with random integer weights between 1 and 20:

import random
import igraph as ig
import matplotlib.pyplot as plt

# Generate grid graph with random weights

g = ig.Graph.Lattice([5, 5], circular=False)["weight"] = [random.randint(1, 20) for _ in]

We then call spanning_tree(), making sure to pass in the randomly generated weights.

# Generate spanning tree
spanning_tree = g.spanning_tree(weights=None, return_tree=False)

Finally, we generate the plot the graph and visualise the spanning tree. We also print out the sum of the edges in the MST.

# Plot graph["color"] = "lightgray"[spanning_tree]["color"] = "midnightblue"["width"] = 0.5[spanning_tree]["width"] = 3.0

fig, ax = plt.subplots()

# Print out minimum edge weight sum
print("Minimum edge weight sum:", sum([mst_edges]["weight"]))

The final plot looks like this:

A visual representation of the spanning tree generated from a grid graph

Minimum spanning tree edges are bolded.

… and the output looks like this:

Minimum edge weight sum: 136


The randomised weights may vary depending on the machine that you run this code on.