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

FuncAnimation无法显示动画问题求助

问题:Matplotlib动画交互式显示异常

我在另一台机器上运行如下代码:

%matplotlib widget

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

n = 100
x = np.random.randn(n)

def update(curr):
    if curr == n:
        a.event_source.stop()
    plt.cla()
    bins = np.arange(-4, 4, 0.5)
    plt.hist(x[:curr], bins=bins)
    plt.axis([-4,4,0,30])
    plt.gca().set_title('Sampling the Normal Distribution')
    plt.gca().set_ylabel('Frequency')
    plt.gca().set_xlabel('Value')
    plt.annotate('n = {}'.format(curr), [3,27])
a = animation.FuncAnimation(plt.figure(), update, interval=100)

plt.show()

每次运行都会出现异常显示,有时还会弹出警告:

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().

我试过安装ipympl、重启内核、IDE及电脑,移除%matplotlib widget,都没有效果。

更新测试发现:

  • 包括此代码在内的所有代码,保存为mp4、html等格式时都能生成正确的动画;
  • 若保存动画,plt.show()会显示最后一帧;若不保存,则显示异常状态。

解决方案

1. 固定动画与Figure的引用关系

代码中隐式创建Figure对象可能导致生命周期不匹配,建议显式创建Figure并绑定动画:

%matplotlib widget

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

n = 100
x = np.random.randn(n)

def update(curr):
    if curr == n:
        a.event_source.stop()
    plt.cla()
    bins = np.arange(-4, 4, 0.5)
    plt.hist(x[:curr], bins=bins)
    plt.axis([-4,4,0,30])
    plt.gca().set_title('Sampling the Normal Distribution')
    plt.gca().set_ylabel('Frequency')
    plt.gca().set_xlabel('Value')
    plt.annotate('n = {}'.format(curr), [3,27])

# 显式创建Figure,确保动画能持续引用它
fig = plt.figure()
a = animation.FuncAnimation(fig, update, interval=100)

plt.show()

2. 切换交互式后端

widget后端可能在当前环境存在兼容性问题,尝试替换为其他后端:

  • 替换开头的%matplotlib widget为%matplotlib tk(依赖Tkinter,多数Python环境默认预装)
  • 或替换为%matplotlib qt(需提前安装PyQt/PySide:pip install pyqt5)

3. 更新依赖版本

版本不兼容是常见诱因,执行以下命令更新相关包:

pip install --upgrade matplotlib ipympl ipywidgets

如果是Jupyter环境,额外执行:

jupyter nbextension enable --py widgetsnbextension

4. 调整动画渲染参数

添加blit=False关闭增量渲染(可能降低性能,但能解决部分渲染异常):

a = animation.FuncAnimation(fig, update, interval=100, blit=False)

内容的提问来源于stack exchange,提问作者Николай Чурилов

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 15:45:53