注意
跳到末尾下载完整的示例代码。
3D 旋转和随机游走的动画#
以 3D 光谱布局绘制图的 3D 图动画示例。遵循 https://gallery.sphinx-doc.cn/stable/auto_examples/plot_8_animations.html,使用初始图的帧旋转(如 https://matplotlib.net.cn/stable/api/animation_api.html 中所述),或完全重绘帧以绘制图上的随机游走。
在本地运行时,需要在两个示例中将带有 'plt.show()' 的注释行取消注释。
import numpy as np
import networkx as nx
import random
import matplotlib.pyplot as plt
from matplotlib import animation
定义要绘制的图。#
选择一个在 3D 中看起来不错的图。
旋转 3D 图动画。#
在此示例中,帧更新仅是对给定 3D 图的旋转。
def init():
ax.scatter(*nodes.T, alpha=0.2, s=100, color="blue")
for vizedge in edges:
ax.plot(*vizedge.T, color="gray")
ax.grid(False)
ax.set_axis_off()
plt.tight_layout()
return
def _frame_update(index):
ax.view_init(index * 0.2, index * 0.5)
return
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ani = animation.FuncAnimation(
fig,
_frame_update,
init_func=init,
interval=50,
cache_frame_data=False,
frames=100,
)
# plt.show()
旋转 3D 图上的随机游走动画。#
帧更新也可以在每一帧中绘制新图,这提供了极致的灵活性,但以性能损失为代价。
def _frame_update(index):
ax.clear()
ax.scatter(*nodes.T, alpha=0.2, s=100, color="blue")
for vizedge in edges:
ax.plot(*vizedge.T, color="gray")
neighbors = list(G.neighbors(node[0]))
if index % 5 == 0:
node[0] = random.choice(neighbors)
node0 = nodes[node[0]]
ax.scatter(*node0, alpha=1, marker="s", color="red", s=100)
ax.view_init(index * 0.2, index * 0.5)
ax.grid(False)
ax.set_axis_off()
plt.tight_layout()
return
fig = plt.figure()
ax = fig.add_subplot(111, projection="3d")
ax.grid(False)
ax.set_axis_off()
plt.tight_layout()
node = [0]
ani = animation.FuncAnimation(
fig,
_frame_update,
interval=50,
cache_frame_data=False,
frames=100,
)
# plt.show()
脚本总运行时间: (0 分 29.646 秒)