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