python-igraph 手册

用于从 Python 使用 igraph

环形图动画

环形图动画

此示例演示了如何使用 Matplotlib 的动画特性来动画显示按顺序揭示的环形图。

import igraph as ig
import matplotlib.pyplot as plt

# Animate a directed ring graph
g = ig.Graph.Ring(10, directed=True)

# Make 2D ring layout
layout = g.layout_circle()

# Create canvas
fig, ax = plt.subplots()
ax.set_aspect(1)

# Prepare interactive backend for autoupdate
plt.ion()
plt.show()

# Animate, one vertex at a time
for frame in range(11):
    # Remove plot elements from the previous frame
    ax.clear()

    # Fix limits (unless you want a zoom-out effect)
    ax.set_xlim(-1.5, 1.5)
    ax.set_ylim(-1.5, 1.5)

    # Plot subgraph
    gd = g.subgraph(range(frame))
    ig.plot(gd, target=ax, layout=layout[:frame], vertex_color="yellow")

    # matplotlib animation infrastructure
    fig.canvas.draw_idle()
    fig.canvas.start_event_loop(0.5)

收到的输出是

The visualisation of a animated ring graph

按顺序动画显示的环形图

注意

我们使用 igraphGraph.subgraph() (参见 induced_subgraph()) 来一次获取环形图的一部分用于每一帧。