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

Windows10下Jupyter Lab提示Javascript Error: IPython is not defined问题求助

Jupyter Lab中运行Matplotlib动画报错:Javascript Error: IPython is not defined

问题重现

将Jupyter Notebook创建的含Matplotlib动画的文件放到Windows10的Jupyter Lab中运行时,触发以下错误:

Javascript Error: IPython is not defined

同时伴随Matplotlib的警告:

C:\Users\marc_arias\AppData\Local\Programs\Python\Python311\Lib\site-packages\matplotlib\animation.py:879: UserWarning: Animation was deleted without rendering anything. This is most likely not intended. To prevent deletion, assign the Animation to a variable, e.g. `anim`, that exists until you output the Animation using `plt.show()` or `anim.save()`.
  warnings.warn(

运行的代码如下:

%matplotlib notebook
import itertools
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.animation as animation

def data_gen():
    for cnt in itertools.count():
        t = cnt / 10
        yield t, np.sin(2*np.pi*t) * np.exp(-t/10.)

def init():
    ax.set_ylim(-1.1, 1.1)
    ax.set_xlim(0, 1)
    del xdata[:]
    del ydata[:]
    line.set_data(xdata, ydata)
    return line,

fig, ax = plt.subplots()
line, = ax.plot([], [], lw=2)
ax.grid()
xdata, ydata = [], []

def run(data):
    t, y = data
    xdata.append(t)
    ydata.append(y)
    xmin, xmax = ax.get_xlim()

    if t >= xmax:
        ax.set_xlim(xmin, 2*xmax)
        ax.figure.canvas.draw()
    line.set_data(xdata, ydata)

    return line,

ani = animation.FuncAnimation(fig, run, data_gen, interval=100, init_func=init,
                              save_count=100)
plt.show()

原因分析

  • %matplotlib notebook是为传统Jupyter Notebook设计的交互式后端,依赖旧版IPython暴露的全局JavaScript对象IPython。
  • Jupyter Lab的前端架构完全重构,不再提供这个全局IPython对象,导致渲染动画时触发JS错误。
  • 动画被删除的警告是前端渲染失败的连锁反应:因为JS错误导致动画无法输出,Python端的动画对象被垃圾回收。

解决方案

  1. 替换Matplotlib后端
    把代码开头的%matplotlib notebook替换为Jupyter Lab兼容的交互式后端:

    %matplotlib widget
    

    这个后端是matplotlib官方推荐的Jupyter Lab交互式渲染方案,支持动画、交互操作,不依赖旧版IPython JS API。

  2. 安装必要依赖(如果widget后端不可用)
    如果运行%matplotlib widget提示错误,需要先安装ipympl包:

    pip install ipympl
    

    安装完成后重启Jupyter Lab,再运行代码即可正常渲染动画。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 16:05:16