FuncAnimation不显示功能之外

时间:2018-01-10 13:32:41

标签: python matplotlib

我对这个thread给出了答案,谈论matplotlib上的淡化点。我对ImportanceOfBeingErnest的答案感到好奇。所以我试着玩他的代码。

首先,这是我的代码。

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。

由于FuncAnimation要求figure运行动画,我想知道为什么plt.show()适用于位置1,而不是位置2。

2 个答案:

答案 0 :(得分:2)

关于FuncAnimation

matplotlib documentation
  

保持对实例对象的引用至关重要。动画由计时器(通常来自主机GUI框架)进行推进,动画对象保存唯一的引用。如果你没有对Animation对象的引用,那么它(以及定时器)将被垃圾收集,这将停止动画。

如果你将plt.show()放在anim_random_points函数之外,那么保存对动画的引用的变量ani将被垃圾收集,并且不会显示任何动画更多。

该案例的解决方案是从该函数返回动画

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

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

答案 1 :(得分:1)

你应该问两个单独的问题。

我可以回答第一个问题。这两个位置之间的差异是由于ani是函数anim_random_points()的局部变量。当执行到达函数结束时,它会自动删除。因此,位置2中的plt.show()无法显示。

如果你想在位置2使用plt.show(),你需要从函数中返回ani对象,并在代码的主要部分保留对它的引用。

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


if __name__ == '__main__':
    (...)
    ani = anim_random_points(fig, axis)

    #   Position 2 for plt.show()
    plt.show()
相关问题