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

Netgraph动画示例在Jupyter Notebook中无法动态更新的问题求助

Jupyter Notebook中Netgraph动画无法播放的解决方法

针对Mac系统、Python 3.12、Jupyter Notebook 7.2.1环境下,运行Netgraph动画示例仅显示最终状态的问题,可通过以下方案解决:

核心原因

%matplotlib inline后端不支持动态动画渲染,plt.ion()仅适配交互式终端,在Jupyter Notebook环境中无法直接生效。

解决步骤

1. 切换Matplotlib后端

在代码最开头添加支持交互式动画的后端指令:

%matplotlib widget

Jupyter Notebook 7.x版本优先推荐widget后端,它对动画的渲染支持更稳定。

2. 显式触发动画渲染

在代码末尾添加动画展示逻辑,确保Jupyter能正确加载并播放动画:

from IPython.display import display
display(animation)

3. 可选:调整动画渲染参数

如果仍存在播放异常,可尝试关闭blit=True(部分后端对blit优化支持不佳),修改FuncAnimation的参数:

animation = FuncAnimation(fig, update, frames=total_frames, interval=200, blit=False)

修改后的完整代码

%matplotlib widget
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
from matplotlib.animation import FuncAnimation
from netgraph import Graph

# Simulate a dynamic network with
# - 5 frames / network states,
# - with 10 nodes at each time point,
# - an expected edge density of 25%, and
# - edge weights drawn from a Gaussian distribution.
total_frames = 5
total_nodes = 10
adjacency_matrix = np.random.rand(total_nodes, total_nodes) < 0.25
weight_matrix = np.random.randn(total_frames, total_nodes, total_nodes)

# Normalise the weights, such that they are on the interval [0, 1].
# They can then be passed directly to matplotlib colormaps (which expect floats on that interval).
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()
g = Graph(adjacency_matrix, edge_cmap=cmap, arrows=True, ax=ax)

def update(ii):
    artists = []
    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)) # np.abs(w-0.5) so that large negative edges are also wide
        artists.append(artist)
    return artists

animation = FuncAnimation(fig, update, frames=total_frames, interval=200, blit=True)
display(animation)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 14:47:44