加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – for循环中的Matplotlib动画?

发布时间:2020-12-20 13:08:03 所属栏目:Python 来源:网络整理
导读:我试图通过动画在for循环中绘制一些数据.我希望它等到动画结束然后继续进行for循环.暂停似乎有效,但有时电影很长,我想关闭并转移到下一个.谁知道我怎么能做到这一点? import numpy as npfrom matplotlib import pyplot as pltfrom matplotlib import animat
我试图通过动画在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,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异常移动到下一个图.
为了更好的可读性,将绘图移动到一个函数中:

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,256)

    ax = plt.axes(xlim=(0,2))
    line,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,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,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>两次跳到下一个动画.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读