I am making a animated bar plot for basic bubble sort. It runs pretty good. But doesn't repeat itself (loop). I am trying it in jupyter notebook, I added %matplotlib qt , Why won't my animFunc repeat although I have set the repeat to True.
x=["1","2","3","4","5","6","7","8","9","10"]
y=[7,8,5,3,1,9,4,2,10,6]
temp=0
def animator_X():
for a in range(len(y)-1):
for b in range(len(y)-a-1):
if y[b]>y[b+1]:
temp = y[b]
y[b]=y[b+1]
y[b+1]=temp
yield y
fig,ax = plt.subplots(figsize=(7,5))
def init():
ax.clear()
y=[7,8,5,3,1,9,4,2,10,6]
plt.bar(x,y,color=['blue'])
def animX(i):
ax.clear()
plt.bar(x,y,color=['blue'])
return plt
animx = FuncAnimation(fig,animX,frames=animator_X,interval=1000,init_func=init,repeat=True)
plt.show()
You aren't resetting the global y variable when it repeats the init after a run.
Try:
%matplotlib notebook
import matplotlib.pyplot as plt
import matplotlib.animation as animation
x=["1","2","3","4","5","6","7","8","9","10"]
y=[7,8,5,3,1,9,4,2,10,6]
temp=0
def animator_X():
for a in range(len(y)-1):
for b in range(len(y)-a-1):
if y[b]>y[b+1]:
temp = y[b]
y[b]=y[b+1]
y[b+1]=temp
print(y)
yield y
fig,ax = plt.subplots(figsize=(7,5))
def init():
global y
ax.clear()
y=[7,8,5,3,1,9,4,2,10,6]
plt.bar(x,y,color=['blue'])
return plt
def animX(i):
ax.clear()
plt.bar(x,y,color=['blue'])
return plt
animp = animation.FuncAnimation(fig,animX,frames=animator_X,interval=100,init_func=init)
plt.show()
That code will run in sessions launched from here . Go there and press launch binder
. When it comes up, you can paste in the code.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.