环图动画

本示例演示了如何使用 matplotlib.animation 以动画形式逐步揭示环图。

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

创建一个环图,然后我们将对其进行动画处理

g = ig.Graph.Ring(10, directed=True)

计算一个看起来像实际环的二维环形布局

准备一个更新函数。这个“回调”函数将在每一帧运行,并将帧号作为单个参数。为了简化,在每一帧中我们只计算包含一部分顶点和边的子图。随着时间的推移,图会变得越来越完整,直到整个环闭合。

注意

动画的开头和结尾有些棘手,因为每次只添加一个顶点或一条边,而不是同时添加。如果您不能立即理解所有细节,请不用担心。

def _update_graph(frame):
    # 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)

    if frame < 10:
        # Plot subgraph
        gd = g.subgraph(range(frame))
    elif frame == 10:
        # In the second-to-last frame, plot all vertices but skip the last
        # edge, which will only be shown in the last frame
        gd = g.copy()
        gd.delete_edges(9)
    else:
        # Last frame
        gd = g

    ig.plot(gd, target=ax, layout=layout[:frame], vertex_color="yellow")

    # Capture handles for blitting
    if frame == 0:
        nhandles = 0
    elif frame == 1:
        nhandles = 1
    elif frame < 11:
        # vertex, 2 for each edge
        nhandles = 3 * frame
    else:
        # The final edge closing the circle
        nhandles = 3 * (frame - 1) + 2

    handles = ax.get_children()[:nhandles]
    return handles

运行动画

fig, ax = plt.subplots()
ani = animation.FuncAnimation(fig, _update_graph, 12, interval=500, blit=True)
plt.ion()
plt.show()

注意

我们使用 igraphGraph.subgraph()(参见 igraph.GraphBase.induced_subgraph())来在每一帧中获取环图的一部分。虽然对于一个简单示例来说已经足够,但这种方法效率不高。思考更有效的方法,例如零半径顶点,是学习 igraph 和 matplotlib 组合的一个有益练习。

脚本总运行时间:(0 分 2.352 秒)

此图库由 Sphinx-Gallery 生成