File: spanning_trees.py

package info (click to toggle)
python-igraph 0.11.9%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 3,480 kB
  • sloc: ansic: 24,611; python: 21,748; sh: 111; makefile: 35; sed: 2
file content (62 lines) | stat: -rw-r--r-- 1,786 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
"""
.. _tutorials-spanning-trees:

==============
Spanning Trees
==============

This example shows how to generate a spanning tree from an input graph using :meth:`igraph.Graph.spanning_tree`. For the related idea of finding a *minimum spanning tree*, see :ref:`tutorials-minimum-spanning-trees`.
"""
import igraph as ig
import matplotlib.pyplot as plt
import random

# %%
# First we create a two-dimensional, 6 by 6 lattice graph:
g = ig.Graph.Lattice([6, 6], circular=False)

# %%
# We can compute the 2D layout of the graph:
layout = g.layout("grid")

# %%
# To spice things up a little, we rearrange the vertex ids and compute a new
# layout. While not terribly useful in this context, it does make for a more
# interesting-looking spanning tree ;-)
random.seed(0)
permutation = list(range(g.vcount()))
random.shuffle(permutation)
g = g.permute_vertices(permutation)
new_layout = g.layout("grid")
for i in range(36):
    new_layout[permutation[i]] = layout[i]
layout = new_layout

# %%
# We can now generate a spanning tree:
spanning_tree = g.spanning_tree(weights=None, return_tree=False)

# %%
# Finally, we can plot the graph with a highlight color for the spanning tree.
# We follow the usual recipe: first we set a few aesthetic options and then we
# leverage :func:`igraph.plot() <igraph.drawing.plot>` and matplotlib for the
# heavy lifting:
g.es["color"] = "lightgray"
g.es[spanning_tree]["color"] = "midnightblue"
g.es["width"] = 0.5
g.es[spanning_tree]["width"] = 3.0

fig, ax = plt.subplots()
ig.plot(
    g,
    target=ax,
    layout=layout,
    vertex_color="lightblue",
    edge_width=g.es["width"]
)
plt.show()

# %%
# .. note::
#   To invert the y axis such that the root of the tree is on top of the plot,
#   you can call `ax.invert_yaxis()` before `plt.show()`.