为兰登制作动画';使用Matplotlib在Python中使用s Ant
在处理ProjectEuler的一些问题时,我遇到了这样一个问题,并认为尝试用Python编写它的动画将是一个好主意。作为基础,我使用了matplotlib函数动画,这篇文章中可以看到一个很好的例子 我已经设法使一个版本工作,代码如下所示。这个想法是用一个大矩阵来模拟蚂蚁移动的黑白网格,并用“imshow”来绘制该矩阵为兰登制作动画';使用Matplotlib在Python中使用s Ant,python,animation,matplotlib,Python,Animation,Matplotlib,在处理ProjectEuler的一些问题时,我遇到了这样一个问题,并认为尝试用Python编写它的动画将是一个好主意。作为基础,我使用了matplotlib函数动画,这篇文章中可以看到一个很好的例子 我已经设法使一个版本工作,代码如下所示。这个想法是用一个大矩阵来模拟蚂蚁移动的黑白网格,并用“imshow”来绘制该矩阵 import numpy as np from matplotlib import pyplot as plt from matplotlib import animation
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# Initialize the Simulation
dim=50
a=np.matrix(np.zeros((dim,dim)))
pos=np.matrix([[dim//2],[dim//2]]) # current position of ant
direction=np.matrix([[1],[0]]) # direction ant is currently moving
#Rotation Matrices
clock=np.matrix([[0,1],[-1,0]])
counter=np.matrix([[0,-1],[1,0]])
def takestep(a,pos,direction):
pos[:]=pos+direction
if a[pos[0,0],pos[1,0]]==0: #landed on white
a[pos[0,0],pos[1,0]]=1
direction[:]=clock*direction
else:
a[pos[0,0],pos[1,0]]=0
direction[:]=counter*direction
#Plotting
fig = plt.figure()
im=plt.imshow(a,interpolation='none')
def init():
im=plt.imshow(a,interpolation='none')
return [im]
def animate(i):
takestep(a,pos,direction)
im=plt.imshow(a,interpolation='none')
#im.set_data(np.array(a))
return [im]
anim = animation.FuncAnimation(fig, animate, init_func=init,
frames=200, interval=0, blit=True)
此代码是功能性的,但我不清楚某些方面:
- 动画连续运行(直到蚂蚁出界)并 200帧后不会重置
- 即使将“间隔”设置为0,动画也会非常缓慢地运行,大约每秒更新两次
- 我想我可以通过使用im.set_data()函数(在代码中注释掉)来加速它,但在我的实现中这不起作用(不变的可视化)
Raphael以下是如何使用
im.set\u data
来提高帧数/秒
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation
# Initialize the Simulation
dim = 50
a = np.matrix(np.zeros((dim, dim)))
pos = np.matrix([[dim // 2], [dim // 2]]) # current position of ant
direction = np.matrix([[1], [0]]) # direction ant is currently moving
# Rotation Matrices
clock = np.matrix([[0, 1], [-1, 0]])
counter = np.matrix([[0, -1], [1, 0]])
def takestep(a, pos, direction):
pos[:] = pos + direction
if a[pos[0, 0], pos[1, 0]] == 0: # landed on white
a[pos[0, 0], pos[1, 0]] = 1
direction[:] = clock * direction
else:
a[pos[0, 0], pos[1, 0]] = 0
direction[:] = counter * direction
fig = plt.figure()
im = plt.imshow(a, interpolation='none', vmin=0, vmax=1)
def animate(i):
takestep(a, pos, direction)
im.set_data(a)
return [im]
anim = animation.FuncAnimation(fig, animate,
frames=200, interval=0, blit=True,
repeat=False)
plt.show()
- 使用
在200帧后停止动画repeat=False
- 在对
的初始调用中设置imshow
。对vmin=0,vmax=1
的初始调用将设置plt.imshow
和vmin
,它们控制值和颜色之间的对应关系。该设置用于imshow AxesImage的所有后续渲染。由于初始vmax
使用所有零数据,plt.imshow
和vmin
都设置为0(初始数据的最小值和最大值)。这使得所有值显示为相同的颜色。因此,为了防止这种情况发生,请自己提供vmax
和vmin
vmax