You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Netgraph动画技术咨询:如何在图表标题中显示帧号

动态网络动画中添加帧号到标题的简便实现方法

要在动画标题里显示当前帧号,只需两步修改:

  1. 保存标题对象:创建标题时将其赋值给变量,方便后续更新
  2. 在update函数中更新标题文本:同时把标题对象加入返回的artists列表(因为开启了blit=True,所有动态变化的元素都必须包含在内,否则标题不会刷新)

修改后的完整代码如下:

import numpy as np
import matplotlib.pyplot as plt

from matplotlib.animation import FuncAnimation
from netgraph import Graph

# 模拟动态网络参数
total_frames = 10
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]区间,适配matplotlib色卡
vmin, vmax = -2, 2
weight_matrix[weight_matrix<vmin] = vmin
weight_matrix[weight_matrix>vmax] = vmax
weight_matrix -= vmin
weight_matrix /= vmax - vmin

cmap = plt.cm.RdGy

fig, ax = plt.subplots()
# 修改点1:保存标题对象,初始显示第0帧
title = fig.suptitle('Simulation viz @ t=0', x=0.15, y=0.95)
g = Graph(adjacency_matrix, node_labels=NODE_LABELS,
            node_layout = NODE_POS, edge_cmap=cmap, arrows=True, ax=ax)

def update(ii):
    artists = []
    # 修改点2:更新标题文本,并将标题对象加入artists列表
    title.set_text(f'Simulation viz @ t={ii}')
    artists.append(title)
    
    for jj, kk in zip(*np.where(adjacency_matrix)):
        w = weight_matrix[ii, jj, kk]
        artist = g.edge_artists[(jj, kk)]
        artist.set_facecolor(cmap(w))
        artist.update_width(0.03 * np.abs(w-0.5))
        artists.append(artist)
    return artists

animation = FuncAnimation(fig, update, frames=total_frames, interval=200, blit=True, repeat=False)
plt.show()

关键注意点

  • 启用blit=True时,Matplotlib仅重绘update函数返回的artists列表中的元素,因此必须将标题对象加入列表才能实现动态更新
  • 初始标题直接设置为t=0,与第一帧内容对应,避免开头显示空白帧号

内容的提问来源于stack exchange,提问作者carpediem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 17:30:09