Spyder 4.1.5中Matplotlib FuncAnimation动画不生效问题求助
Matplotlib动画不运行问题排查与解决
问题根因
问题由两个常见原因共同导致:
- Spyder 4.1.5默认使用Inline后端渲染Matplotlib图像,该后端仅支持输出静态图片,无法实现动画的动态刷新效果
- 代码中生成的
FuncAnimation动画对象没有被强引用持有,会被Python垃圾回收机制提前销毁,导致animate回调函数完全不会被触发
解决步骤
1 调整Spyder图形后端配置
打开配置路径:工具 > 偏好设置 > IPython控制台 > 图形,将后端选项从「Inline」修改为「Automatic」或「Qt5Agg」,修改后重启Spyder生效,改动后Matplotlib会弹出独立的绘图窗口,支持动画动态渲染。
2 修正代码避免动画对象被回收
在原有代码基础上新增一行,强制持有动画对象的引用即可,修正后的完整代码如下:
import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from itertools import count import random xcord = [] ycord = [5] index = count() xcord.append(next(index)) def animate(i): xcord.append(next(index)) ycord.append(random.randint(0,5)) print(xcord) print(ycord) plt.cla() plt.plot(xcord,ycord) fig, ax = plt.subplots(1,1) print(xcord) print(ycord) ani = FuncAnimation(fig,animate,interval=1000) # 新增行:强制持有动画对象的引用,避免被垃圾回收 globals()['ani'] = ani plt.tight_layout() plt.show()
修改完成后重新运行代码,即可看到随时间更新的折线动画,控制台也会持续打印xcord和ycord的更新结果。
内容的提问来源于stack exchange,提问作者Peter John.V.
相关产品推荐
相关产品推荐

