首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在动画中使用matplotlib时的内存泄漏

在动画中使用matplotlib时的内存泄漏
EN

Stack Overflow用户
提问于 2017-11-30 16:38:07
回答 1查看 481关注 0票数 1

最近,我正在使用python和matplotlib制作动画。在开始时,我遵循了在网络中搜索的示例,它具有以下结构:

代码语言:javascript
复制
=========================================================================
import matplotlib.pyplot as plot
import matplotlib.animation as anim

def animate(i):
    ax.clear()
    # Re-plot the figure with updated animation data

if __name__ == "__main__":
    fig, ax = plot.subplots(fsigsize=(8,4))
    an = anim.FuncAnimation(fig, animate, interval=1)
    plot.show()
=========================================================================

这段代码看起来没问题。没有内存泄漏。但问题是它运行得太慢了。因为当使用更新的动画数据重新生成绘图时,绘图的所有设置(例如,set_xlim()、set_ylim()、绘图轴、...等等)必须一遍又一遍地做。因此,我尝试用这种方式来提高性能:

代码语言:javascript
复制
========================================================================
import matplotlib.pyplot as plot
import matplotlib.animation as anim

def init():
    ax.set_title("....")
    ax.set_xlim(-1, 1)
    ax.set_ylim(-10,10)
    # plot axes, and all the patterns which are fixed in the animation

def animate(i):
    # x[] and y[] are large arrays with updated animation data
    if ('la' in globals()): la.remove()
    la, = ax.plot(x, y)

if __name__ == "__main__":
    fig, ax = plot.subplots(figsize=(8,4))
    an = anim.FuncAnimation(fig, animate, init_func=init, interval=1)
    plot.show()
========================================================================

以这种方式,只有主曲线"la“被重新绘制。其他固定部分在init()子例程中只执行一次。现在动画运行得更快了。但是出现了严重的内存泄漏。在动画中运行"top“,我看到占用的内存不断增长。经过测试,我确信这条语句是内存泄漏的来源:

代码语言:javascript
复制
la, = ax.plot(x, y)

一些讨论表明,内存泄漏是由于绘图"ax“未关闭所致。但是,如果我每次都关闭绘图来更新图形,那么性能就会变得太慢。

有没有更好的方法来解决这个问题?

我的环境: Python 3.4,matplotlib-1.4.2,Debian GNU/Linux 8.8。我也在Cygwin和MacOS X下测试了Python3.6,matplotlib-2.1.0,情况是一样的。

非常感谢你的帮助。

T.H.Hsieh

EN

回答 1

Stack Overflow用户

发布于 2017-11-30 17:49:08

对不起,我刚刚想出了答案。在动画中更新绘图的正确方法应该是“设置新数据”,而不是“移除并重新绘制曲线”或“重新生成绘图”。因此,我的代码应该改为:

代码语言:javascript
复制
=====================================================================
import matplotlib.pyplot as plot
import matplotlib.animation as anim

def init():
    global ax, la
    ax.set_title("....")
    ax.set_xlim(-1, 1)
    ax.set_ylim(-10,10)
    # get the initial data x[], y[] to plot the initial curve
    la, = ax.plot(x, y, color="red", lw=1)

def animate(i):
    global fig, la
    # update the data x[], y[], set the updated data, and redraw.
    la.set_xdata(x)
    la.set_ydata(y)
    fig.canvas.draw()

if __name__ == "__main__":
    fig, ax = plot.subplots(fsigsize=(8,4))
    an = anim.FuncAnimation(fig, animate, interval=1)
    plot.show()
=====================================================================    

无论如何,感谢那些给了我评论的人,他们让我找到了答案。

诚挚的问候,

T.H.Hsieh

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47569054

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档