python - FuncAnimation 不显示函数之外

标签 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 放置在动画函数之后,另一个位置按代码方式放置在动画函数之后,因为该函数在位置 1 之后结束,因此转到位置 2。

由于FuncAnimation需要figure来运行动画,我想知道为什么plt.show()在位置1上工作,但不在位置 2 上。

最佳答案

matplotlib documentation关于 FuncAnimation

的说明

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 函数之外,变量 ani 保存对动画的引用,将被垃圾收集,并且将不再显示动画。

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

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

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

关于python - FuncAnimation 不显示函数之外,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55157406/

相关文章:

python - 我无法使用 pip3 安装 onnxruntime。请解决它

python - Matplotlib Specgram 得到与 Matlab 相同的结果

python - 椭圆没有显示 - python matplotlib

python - 绘制租金图

python - Seaborn distplot 与来自不同数组的 rugplot

python - Matplotlib Groupby Graph 中的颜色一致

python - PySimpleGUI,如何让字符串在新行上打印而不是切断它?

python - 如何创建具有动态子属性的@property?

python - 从列表中选择优先项目

python - 使用 Tkinter 在消息框中显示进度