gpt4 book ai didi

python - for循环中的Matplotlib动画?

转载 作者:太空宇宙 更新时间:2023-11-03 12:05:36 24 4
gpt4 key购买 nike

我正在尝试在 for 循环中通过动画绘制一些数据。我希望它等到动画完成,然后在 for 循环中继续。暂停似乎可以做到这一点,但有时电影很长,我想关闭并转到下一部。有人知道我怎样才能做到这一点吗?

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import time

for j in range(0,2):
fig = plt.figure(j)
mngr = plt.get_current_fig_manager()
mngr.window.setGeometry(j*256,0,256, 256)

ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,

# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i+j/4.))
line.set_data(x, y)
return line,

# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True,repeat=False)

plt.pause(0.02*200)

plt.show(block=True)

最佳答案

一种方法是使用 KeyboardInterrupt移动到下一个情节的异常(exception)。为了更好的可读性,将您的绘图移动到一个函数中:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
import time



def animate_multi(j):
fig = plt.figure(j)
mngr = plt.get_current_fig_manager()
mngr.window.setGeometry(j*256,0,256, 256)

ax = plt.axes(xlim=(0, 2), ylim=(-2, 2))
line, = ax.plot([], [], lw=2)

# initialization function: plot the background of each frame
def init():
line.set_data([], [])
return line,

# animation function. This is called sequentially
def animate(i):
x = np.linspace(0, 2, 1000)
y = np.sin(2 * np.pi * (x - 0.01 * i+j/4.))
line.set_data(x, y)
return line,

# call the animator. blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=20, blit=True,repeat=False)

plt.pause(0.02*200)
plt.close()
plt.show(block=True)

现在,在你的循环中除了KeyboardInterrup继续下一个动画:

for j in range(5):
try:
print('Working on plot', j)
animate_multi(j)
except KeyboardInterrupt:
plt.close()

注意:您可能需要按 <Ctrl>-<C>两次跳到下一个动画。

关于python - for循环中的Matplotlib动画?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33193696/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com