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

Jupyter Notebook中Matplotlib动画交互控件无法正常显示求助

问题:Jupyter Notebook中Matplotlib动画无法显示交互控件

我从Matplotlib官方教程复制了以下代码到新的Jupyter Notebook中运行:

%matplotlib notebook

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

fig, ax = plt.subplots()
t = np.linspace(0, 3, 40)
g = -9.81
v0 = 12
z = g * t**2 / 2 + v0 * t

v02 = 5
z2 = g * t**2 / 2 + v02 * t

scat = ax.scatter(t[0], z[0], c="b", s=5, label=f'v0 = {v0} m/s')
line2 = ax.plot(t[0], z2[0], label=f'v0 = {v02} m/s')[0]
ax.set(xlim=[0, 3], ylim=[-4, 10], xlabel='Time [s]', ylabel='Z [m]')
ax.legend()


def update(frame):
    # for each frame, update the data stored on each artist.
    x = t[:frame]
    y = z[:frame]
    # update the scatter plot:
    data = np.stack([x, y]).T
    scat.set_offsets(data)
    # update the line plot:
    line2.set_xdata(t[:frame])
    line2.set_ydata(z2[:frame])
    return (scat, line2)


ani = animation.FuncAnimation(fig=fig, func=update, frames=40, interval=30)
plt.show()

但仅能看到静态图形(单元格标记为*),偶尔重启内核后能看到动画初始帧,但始终无法显示Matplotlib教程中的交互控件。

服务器信息:

  • Jupyter Notebook版本:6.5.4-762f3618
  • Python版本:3.10.6 (main, May 29 2023, 11:10:38) [GCC 11.3.0]
  • 当前内核:同上述Python版本

我可以将动画保存为mp4文件查看,但更希望使用交互功能,请问哪里操作有误?


解决方案

以下是几个可行的调整方案,按优先级尝试:

1. 更换Matplotlib后端

%matplotlib notebook后端在Jupyter Notebook 6.x版本中存在兼容性问题,换成%matplotlib ipympl后端:

  • 先在终端安装依赖:pip install ipympl
  • 将代码开头的%matplotlib notebook替换为%matplotlib ipympl
  • 重启内核后重新运行代码

2. 保留动画对象引用

Jupyter的垃圾回收机制可能会回收未被引用的动画对象,导致无法渲染。在代码末尾添加以下内容:

from IPython.display import display
display(ani)

3. 检查浏览器兼容性

  • 使用Chrome、Firefox等现代浏览器打开Notebook,避免老旧浏览器
  • 禁用浏览器的广告拦截、脚本拦截插件,防止其阻止动画控件加载

4. 升级相关依赖包

更新Matplotlib和Jupyter系列包,修复版本兼容问题:

pip install --upgrade matplotlib ipykernel jupyter notebook

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 16:04:51