
本文详解如何在单个 matplotlib figure 中同时驱动两个独立动画子图:一个基于 netgraph 的动态网络图,另一个为实时更新的正弦/余弦曲线,确保两者帧率一致、渲染高效且代码结构清晰。
本文详解如何在单个 matplotlib figure 中同时驱动两个独立动画子图:一个基于 netgraph 的动态网络图,另一个为实时更新的正弦/余弦曲线,确保两者帧率一致、渲染高效且代码结构清晰。
在科学计算与仿真可视化中,常需将不同维度的动态数据(如拓扑结构演化 + 时序信号变化)统一呈现于同一界面。Matplotlib 的 FuncAnimation 支持多子图协同动画,但关键在于:所有需重绘的 Artist 对象必须在 update() 函数中显式更新,并统一返回为列表,供 blit=True 机制识别脏区域。以下为完整、可运行的实现方案。
✅ 核心要点与结构设计
-
双子图布局:使用
plt.subplot2grid精确划分空间,左侧大图展示网络拓扑(ax1),右侧小图绘制时序曲线(ax2); -
Artist 预初始化:
netgraph.Graph实例化后,其边对象(edge_artists)和ax2上的Line2D对象(line_sin,line_cos)均需在update()外完成创建; -
统一时间轴驱动:
frames=total_frames控制总帧数,ii参数同步驱动网络权重切换与曲线相位偏移; -
blit=True兼容性:所有被修改的 Artist(包括g.edge_artists成员及line_sin/line_cos)必须在update()返回值中显式列出,否则部分元素将无法刷新。
? 完整可执行代码
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from netgraph import Graph
# --- 数据模拟 ---
total_frames = 21
total_nodes = 5
NODE_LABELS = {0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E'}
NODE_POS = {
0: (0.0, 0.5),
1: (0.65, 0.25),
2: (0.7, 0.5),
3: (0.5, 0.75),
4: (0.25, 0.25)
}
adjacency_matrix = np.random.rand(total_nodes, total_nodes) < 0.25
weight_matrix = np.random.randn(total_frames, total_nodes, total_nodes)
# 归一化权重至 [0, 1]
vmin, vmax = -2, 2
weight_matrix = np.clip(weight_matrix, vmin, vmax)
weight_matrix = (weight_matrix - vmin) / (vmax - vmin)
cmap = plt.cm.RdGy
# --- 图形初始化 ---
fig = plt.figure(figsize=(11, 6))
ax1 = plt.subplot2grid((6, 11), (0, 0), rowspan=6, colspan=5) # 网络图
ax2 = plt.subplot2grid((6, 11), (1, 6), rowspan=2, colspan=5) # 曲线图
# 清除坐标轴刻度(提升视觉专注度)
for ax in fig.axes:
ax.tick_params(labelbottom=False, labelleft=False)
ax1.set_title('Simulation viz', x=0.25, y=1.25, fontsize=12)
ax2.set_title('Flow @t', x=0.15, y=1.25, fontsize=12)
# 初始化网络图
g = Graph(
adjacency_matrix,
node_labels=NODE_LABELS,
node_layout=NODE_POS,
edge_cmap=cmap,
arrows=True,
ax=ax1
)
# 初始化曲线图(空数据)
x = np.linspace(0, 2*np.pi, 100)
line_sin, = ax2.plot([], [], 'b-', label='sin(x)', linewidth=1.5)
line_cos, = ax2.plot([], [], 'r--', label='cos(x)', linewidth=1.5)
ax2.set_xlim(0, 2*np.pi)
ax2.set_ylim(-1.5, 1.5)
ax2.legend(loc='upper right', fontsize=9)
# --- 动画更新函数 ---
def update(ii):
artists = []
# 更新网络边颜色与宽度
for jj, kk in zip(*np.where(adjacency_matrix)):
w = weight_matrix[ii, jj, kk]
edge_artist = g.edge_artists[(jj, kk)]
edge_artist.set_facecolor(cmap(w))
edge_artist.update_width(0.03 * np.abs(w - 0.5))
artists.append(edge_artist)
# 更新曲线数据(相位随帧递增)
phase = ii * 0.2
y_sin = np.sin(x + phase)
y_cos = np.cos(x + phase)
line_sin.set_data(x, y_sin)
line_cos.set_data(x, y_cos)
artists.extend([line_sin, line_cos])
return artists # ⚠️ 必须返回全部被修改的 Artist!
# --- 启动动画 ---
anim = FuncAnimation(
fig,
update,
frames=total_frames,
interval=200,
blit=True,
repeat=False
)
plt.tight_layout()
plt.show()⚠️ 注意事项与最佳实践
-
blit=True的严格要求:若遗漏任一更新后的 Artist(如忘记append(line_sin)),该元素将冻结不动;调试时可先设blit=False验证逻辑正确性; -
性能优化:
netgraph的update_width()和set_facecolor()均为就地操作,避免重建 Artist;曲线使用set_data()而非重新plot(),显著提升帧率; -
相位控制灵活性:
ii * 0.2可替换为任意时间函数(如ii * 0.05 * np.pi或读取真实仿真时间戳),便于对齐实际物理过程; -
依赖安装:确保已安装
netgraph(pip install netgraph)及兼容版本的matplotlib(≥3.7); -
扩展建议:如需添加节点状态动画、图例动态更新或交互控件,可在
update()中追加对应逻辑并加入artists列表。
通过本方案,您可无缝集成拓扑动画与时序动画,构建专业级多模态仿真可视化系统。

















