FuncAnimation不显示在函数外部 [英] FuncAnimation doesn't show outside of function

查看:75
本文介绍了FuncAnimation不显示在函数外部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对此线程给出了答案,讨论matplotlib上的衰落点.我对ImportanceOfBeingErnest的回答感到很好奇.因此,我尝试使用他的代码.

I gave an answer on this thread, talking about fading point on matplotlib. And I got curious about ImportanceOfBeingErnest's answer. So I tried to play around with his code.

首先,这是我的代码.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation
from matplotlib.colors import LinearSegmentedColormap

def get_new_vals():
    x = 0
    y = 0
    while True:
        if x >= .9:
            x = 0
            y = 0
        x += .1
        y += .1
        yield x, y

def update(t, x_vals, y_vals, intensity, scatter, gen):
    #   Get intermediate points
    new_xvals, new_yvals = gen.next()
    x_vals.extend([new_xvals])
    y_vals.extend([new_yvals])

    #   Put new values in your plot
    scatter.set_offsets(np.c_[x_vals, y_vals])

    #   Calculate new color values
    for index in range(len(intensity)):
        if intensity[index] < .1:
            intensity[index] = 0
        intensity[index] *= .6
    intensity.extend(1 for _ in xrange(len([new_xvals])))

    intens_dup = np.array(intensity)

    """
    intensity = np.concatenate((np.array(intensity) * .6, np.ones(len(new_xvals))))
    """
    scatter.set_array(intens_dup)

    # Set title
    axis.set_title('Time: %0.3f' % t)

def anim_random_points(fig, axis):
    x_vals = []
    y_vals = []
    intensity = []
    iterations = 100

    colors = [ [0, 0, 1, 0], [0, 0, 1, 0.5], [0, 0.2, 0.4, 1] ]
    cmap = LinearSegmentedColormap.from_list("", colors)
    scatter = axis.scatter(x_vals, y_vals, c=[], cmap=cmap, vmin=0, vmax=1)

    gen_values = get_new_vals()

    ani = matplotlib.animation.FuncAnimation(fig, update, frames=iterations,
        interval=50, fargs=(x_vals, y_vals, intensity, scatter, gen_values),
        repeat=False)

    #   Position 1 for plt.show()
    plt.show()

if __name__ == '__main__':

    fig, axis = plt.subplots()
    axis.set_xlabel('X Axis', size = 12)
    axis.set_ylabel('Y Axis', size = 12)
    axis.axis([0,1,0,1])

    anim_random_points(fig, axis)

    #   Position 2 for plt.show()
    # plt.show()

然后,我注意到了一件奇怪的事情.至少对于我来说.注意Position 1Position 2(在代码末尾).位置1放置在animation函数之后,另一个位置放置在 代码后,因为该函数在位置1之后结束,因此转到位置2.

I, then, noticed an odd thing. At least for me. Notice the Position 1 and Position 2 (at the end of code). The position 1 is placed just after the animation function, the other one is placed just after code-wise, since the function ends after position 1 and therefore goes to position 2.

由于FuncAnimation需要figure才能运行动画,所以我想知道为什么plt.show()可以在位置1上工作,而不在位置2上工作.

Since FuncAnimation requires the figure to run the animation on, I am wondering why the plt.show() works on Position 1, but not on Position 2.

推荐答案

matplotlib文档关于FuncAnimation

保留对实例对象的引用至关重要.动画由计时器(通常来自主机GUI框架)推进,该动画对象持有唯一的引用.如果您没有保留对Animation对象的引用,则该对象(以及计时器)将被垃圾收集,这将停止动画.

It is critical to keep a reference to the instance object. The animation is advanced by a timer (typically from the host GUI framework) which the Animation object holds the only reference to. If you do not hold a reference to the Animation object, it (and hence the timers), will be garbage collected which will stop the animation.

如果将plt.show()放在anim_random_points函数之外,则将保留垃圾内容,该变量保存对动画的引用,并且将不再显示动画.

If you put plt.show() outside of the anim_random_points function, the variable ani, which holds the reference to the animation, will be garbage collected and there will be no animation to be shown any more.

这种情况下的解决方案是从该函数返回动画

The solution for that case would be to return the animation from that function

def anim_random_points(fig, axis):
    # ...
    ani = matplotlib.animation.FuncAnimation(...)
    return ani

if __name__ == '__main__':
    # ...
    ani = anim_random_points(...)
    plt.show()

这篇关于FuncAnimation不显示在函数外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆