简体   繁体   English

Matplotlib animation on spyder python output 单个图像

[英]Matplotlib animation on spyder python output a single image

I wanted to make an animation in spyder but i just get a static plot.我想在 spyder 中制作一个 animation,但我只得到一个 static plot。 this is the code.这是代码。

import numpy as np
import matplotlib.pyplot as plt

plt.figure(1) 
plt.clf() 
plt.axis([-10,10,-10,10]) 
n=10 
pos=(20*np.random.sample(n*2)-10).reshape(n,2) 
vel=(0.3*np.random.normal(size=n*2)).reshape(n,2) 
sizes=100*np.random.sample(n)+100 
colors=np.random.sample([n,4]
circles=plt.scatter(pos[:,0], pos[:,1], marker='o', s=sizes, c=colors) 
for i in range(100):
   pos=pos+vel
   bounce=abs(pos)>10 
   vel[bounce] = -vel[bounce] 
   circles.set_offsets(pos) 
   plt.draw() 
   plt.show() 

this is what i get, I've tried with %matplotlib qt5 but it doesn't change the output and the stays still 1 ] 1这就是我得到的,我已经尝试使用 %matplotlib qt5 但它不会改变 output 并且仍然保持1 ] 1

There are two things you need to do to make the animation work.要使 animation 工作,您需要做两件事。

  • First, is that you need to show the figure once the animation made, so plt.show() should get out of the for loop.首先,您需要在 animation 制作后显示该图,因此plt.show()应该退出for循环。
  • Also to be able to see the frames, you need to put a small amount of time between them, which an be achieved by adding, for example, plt.pause(t) ( t in seconds) in between the frames.此外,为了能够看到帧,您需要在它们之间放置少量时间,这可以通过在帧之间添加例如plt.pause(t) t以秒为单位的 t)来实现。

The code shown below is the edited code generating an animated plot.下面显示的代码是生成动画 plot 的编辑代码。

import numpy as np
import matplotlib.pyplot as plt

plt.figure(1)
plt.clf()
plt.axis([-10,10,-10,10])
n=10
pos=(20*np.random.sample(n*2)-10).reshape(n,2)
vel=(0.3*np.random.normal(size=n*2)).reshape(n,2)
sizes=100*np.random.sample(n)+100
colors=np.random.sample([n,4])
circles=plt.scatter(pos[:,0], pos[:,1], marker='o', s=sizes, c=colors)
for i in range(100):
   pos=pos+vel
   bounce=abs(pos)>10
   vel[bounce] = -vel[bounce]
   circles.set_offsets(pos)
   plt.draw()
   plt.pause(0.05)
plt.show()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM