1 回答
TA贡献1839条经验 获得超15个赞
我发现,这不是plt.imshow()和 动画同时出现的问题,而是我的循环本身的问题。一旦修好,它就起作用了。这是代码:
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import numpy as np
grid = np.zeros((11,11), dtype=np.int16)
def neighbors(x,y):
#cell = grid[x,y]
n_cells = [grid[x-1, y+1], grid[x, y+1], grid[x+1, y+1],
grid[x-1, y], grid[x+1, y],
grid[x-1, y-1], grid[x, y-1], grid[x+1, y-1]]
return sum(n_cells)
grid[3:6,5]=1
newgrid = grid.copy()
def updatefig(i):
for x in range(10):
for y in range(10):
if grid[x,y]==0:
if neighbors(x,y)==3:
newgrid[x,y]=1
else:
if neighbors(x,y)<2 or neighbors(x,y)>3:
newgrid[x,y]=0
def update_grid():
global grid
grid = newgrid.copy()
update_grid()
plt.imshow(newgrid, cmap='binary')
ax = plt.gca()
ax.set_xticklabels([])
ax.set_yticklabels([])
ax.set_xticks([])
ax.set_yticks([])
#plt.imshow(grid, cmap='binary')
ani = FuncAnimation(fig, updatefig, interval=100)
plt.show()
我已经imshow在循环内部使用了,但即使我取消注释动画函数上面的那个,它仍然可以工作。
添加回答
举报