注意
Go to the end 下载完整示例代码。
环形图动画
这个例子演示了如何使用matplotlib.animation来顺序显示一个环形图的动画。
import igraph as ig
import matplotlib.pyplot as plt
import matplotlib.animation as animation
创建一个环形图,然后我们将对其进行动画处理
g = ig.Graph.Ring(10, directed=True)
计算一个看起来像实际环的2D环形布局
layout = g.layout_circle()
准备一个更新函数。这个“回调”函数将在每一帧运行,并以帧号作为单一参数。为了简化,我们在每一帧计算一个只包含部分顶点和边的子图。随着时间的推移,图变得越来越完整,直到整个环闭合。
注意
动画的开始和结束有点棘手,因为只添加了一个顶点或边,而不是两者都添加。如果你不能立即理解所有细节,不要担心。
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()
注意
我们使用igraph的Graph.subgraph()(参见
igraph.GraphBase.induced_subgraph())以便为每一帧获取环形图的一部分。虽然这对于一个简单的例子来说已经足够,但这种方法并不是非常高效。思考更高效的方法,例如半径为0的顶点,是学习igraph和matplotlib结合的有用练习。
脚本的总运行时间: (0 分钟 7.309 秒)