如何从 for 循环内对 matplotlib 绘图进行动画处理

Aes*_*sir 0 python matplotlib matplotlib-animation

我想用 for 循环的每次迭代中计算的值更新我的 matplotlibplot 。我的想法是,我可以实时查看计算了哪些值,并在脚本运行时逐次观察进度迭代。我不想首先迭代循环,存储值,然后执行绘图。

一些示例代码在这里:

from itertools import count
import random

from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt


def animate(i, x_vals, y_vals):
    plt.cla()
    plt.plot(x_vals, y_vals)

if __name__ == "__main__":
    x_vals = []
    y_vals = []
    fig = plt.figure()
    index = count()

    for i in range(10):
        print(i)
        x_vals.append(next(index))
        y_vals.append(random.randint(0, 10))
        ani = FuncAnimation(fig, animate, fargs=(x_vals, y_vals))
        plt.show()
Run Code Online (Sandbox Code Playgroud)

我在网上看到的大多数示例都处理动画的所有内容都是全局变量的情况,我想避免这种情况。当我使用调试器逐行单步执行代码时,该图形确实出现并且是动画的。当我在没有调试器的情况下运行脚本时,会显示图形,但没有绘制任何内容,并且我可以看到我的循环没有超过第一次迭代,首先等待图形窗口关闭,然后继续。

Ima*_*kin 5

在 matplotlib 中制作动画时永远不应该使用循环。

animate函数会根据您的时间间隔自动调用。

像这样的东西应该有效

def animate(i, x=[], y=[]):
    plt.cla()
    x.append(i)
    y.append(random.randint(0, 10))
    plt.plot(x, y)


if __name__ == "__main__":
    fig = plt.figure()
    ani = FuncAnimation(fig, animate, interval=700)
    plt.show()
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,这看起来很有帮助,但我很困惑,因为现在 for 循环消失了(并由 animate 函数控制)。我的循环是程序中主要工作发生的地方,并且计算许多事情。通过这种方法,看起来我必须将所有内循环逻辑放入这个动画函数中,我认为它应该只用于实际的可视化。有没有一个好的方法来分离和组合这些东西?或者将所有内容转储到动画函数中是否可以?这里的最佳实践是什么? (2认同)