This is my script so far:
import numpy as np
import matplotlib.pyplot as plt
import random
t=0
r=3.0
n=0
A=[]
for x in range(10):
for y in range(10):
A.append([random.uniform(0,1),random.uniform(0,1)])
for m in range(len(A)):
plt.plot(A[m][0],A[m][1], "x", color="blue")
plt.show()
while n<=100:
for m in range(len(A)):
A[m][0]=r*A[m][0]*(1-A[m][0])
A[m][1]=r*A[m][1]*(1-A[m][1])
for m in range(len(A)):
plt.plot(A[m][0],A[m][1], "x", color="blue")
plt.show()
n+=1
What I want to do now is animate it, so that I don’t have to close the plot each time it for python to recalculate an show me the next image. Instead, it should show me a new plot every say 5s. What’s the best way for me to do that?
Use
plt.ion()to enable interactive plotting (doesn’t make the execution stop when a plot-window is opened) and then useplt.clf()to clear the plot.A working sample is:
You must use
plt.draw()to force the GUI to update immediately andplt.pause(t)to break for t seconds. Actually, I’m not quite sure how you want to treat the two parts of your script (the two loops containing plot-commands) in terms of animation, but hopefully, my code will guide you the right way.Remarks
First, I’d recommend to stick to some conventions when coding python. Use 4-space indentation, this makes your code much more readable. Second, I’d recommend using numpy for arrays. You import it but you don’t use it. This makes your code definitely faster.
Third and last, are you aware of the signature
plot(x,y,"bx")for matplotlib? I think it’s really convenient.