python – 如何等到matplotlib动画结束?

前端之家收集整理的这篇文章主要介绍了python – 如何等到matplotlib动画结束?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_403_1@请考虑直接从Matplotlib文档中获取的以下代码
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.animation as animation
  4. import time # optional for testing only
  5. import cv2 # optional for testing only
  6.  
  7. fig = plt.figure()
  8.  
  9. def f(x,y):
  10. return np.sin(x) + np.cos(y)
  11.  
  12. x = np.linspace(0,2 * np.pi,120)
  13. y = np.linspace(0,100).reshape(-1,1)
  14.  
  15. im = plt.imshow(f(x,y),animated=True)
  16.  
  17. def updatefig(*args):
  18. global x,y
  19. x += np.pi / 15.
  20. y += np.pi / 20.
  21. im.set_array(f(x,y))
  22. return im,ani = animation.FuncAnimation(fig,updatefig,interval=50,blit=True)
  23. plt.show()

这在我的系统上工作正常.现在,尝试将以下代码附加到上面的代码中:

  1. while True:
  2. #I have tried any of these 3 commands,without success:
  3. pass
  4. #time.sleep(1)
  5. #cv2.waitKey(10)

结果是该程序冻结了.显然,Matplotlib的“Animation”类在一个单独的线程中运行动画.所以我有以下两个问题:

1)如果进程在一个单独的线程中运行,为什么它会受到后续循环的干扰?

2)如何对python说等到动画结束?

解决方法

对我来说,复制到ipython按预期工作(动画首先播放然后是无限循环)但是在运行脚本时它会冻结.

1)我不确定cpython究竟是如何处理多线程的,特别是当与特定的matplotlib后端结合使用时,它似乎在这里失败了.一种可能性是通过使用来明确你想如何使用线程

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.animation as animation
  4. import multiprocessing as mp
  5.  
  6.  
  7. fig = plt.figure()
  8.  
  9. def f(x,#A function to set thread number 0 to animate and the rest to loop
  10. def worker(num):
  11. if num == 0:
  12. ani = animation.FuncAnimation(fig,blit=True)
  13. plt.show()
  14. else:
  15. while True:
  16. print("in loop")
  17. pass
  18.  
  19. return
  20.  
  21.  
  22. # Create two threads
  23. jobs = []
  24. for i in range(2):
  25. p = mp.Process(target=worker,args=(i,))
  26. jobs.append(p)
  27. p.start()

它定义了两个线程并设置一个用于动画,一个用于循环.

2)为了解决这个问题,正如@Mitesh Shah所建议的那样,你可以使用plt.show(block = True).对我来说,脚本然后按照预期的方式运行动画然后循环.完整代码

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.animation as animation
  4.  
  5. fig = plt.figure()
  6.  
  7. def f(x,blit=True)
  8. plt.show(block=True)
  9.  
  10. while True:
  11. print("in loop")
  12. pass

更新:替代方案是简单地使用交互模式,

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. import matplotlib.animation as animation
  4.  
  5. fig = plt.figure()
  6. plt.ion()
  7. plt.show()
  8.  
  9. def f(x,y):
  10. return np.sin(x) + np.cos(y)
  11.  
  12. def updatefig(*args):
  13. global x,y
  14.  
  15.  
  16. x = np.linspace(0,1)
  17. im = plt.imshow(f(x,y))
  18.  
  19. for i in range(500):
  20.  
  21. x += np.pi / 15.
  22. y += np.pi / 20.
  23. im.set_array(f(x,y))
  24. plt.draw()
  25. plt.pause(0.0000001)

猜你在找的Python相关文章