Home > database >  Matplotlib animation on spyder python output a single image
Matplotlib animation on spyder python output a single image

Time:12-06

I wanted to make an animation in spyder but i just get a 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 still1]1

CodePudding user response:

There are two things you need to do to make the animation work.

  • First, is that you need to show the figure once the animation made, so plt.show() should get out of the for loop.
  • 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.

The code shown below is the edited code generating an animated 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()
  • Related