使用Matplotlib在Python中动画兰登的蚂蚁 [英] Animating Langdon's Ant in Python with Matplotlib
问题描述
在Euler项目上遇到了一些问题,我遇到了 Langdon's Ant ,并认为这样做会尝试用Python编写动画的一个好主意。作为基础,我去使用了matplotlib函数动画,可以在此帖子上看到一个非常好的示例此处
doing some problems on Project Euler, I came across Langdon's Ant and thought it would be a nice idea to try to code an animation of it in Python. As a basis, I went and used the matplotlib function animation, a very nice example can be seen on this post here
我设法使一个版本正常工作,代码如下所示。这个想法是用一个大矩阵模拟蚂蚁移动的黑白网格,并用'imshow'绘制该矩阵。
I have managed to get a version working, the code is shown below. The idea is to simulate the black and white grid the ant moves on with a large matrix and plot that matrix with 'imshow'.
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)
此代码可以正常工作,但是我不清楚:
This code is functional, but I'm unclear about somethings:
-
动画连续运行(直到蚂蚁越界)并且
在200帧后不会重置
The animation runs continuously (until the ant is out of bounds) and doesn't reset after 200 frames
即使将间隔设置为0,动画运行也非常缓慢,每秒更新大约两次
Even if the interval is set to 0, the animation runs quite slowly, updateing about twice a second
I认为我可以通过使用im.set_data()函数(在代码中注释掉)来加快速度,但是在我的实现中,此操作不起作用(不变的可视化效果)
I think I can speed it up by using the im.set_data() function (commented out in the code), in my implementation this doesn't work though (unchanging visualization)
那会是gr如果有人可以给我一些如何改进此动画的提示,请先吃点东西!
It would be great if someone could give me some pointers on how to improve this animation, thanks in advance!
最诚挚的问候,
Raphael
Best regards, Raphael
推荐答案
在这里,您可以使用 im.set_data
提高每秒帧数。
Here is how you could use im.set_data
to improve frames/second.
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()
- 使用
repeat = False
在200帧后停止动画。 - 在对
imshow
的初始调用中将vmin = 0,vmax = 1
设置为$。最初调用plt.imshow
会设置vmin
和vmax
,它控制值和颜色之间的对应关系。该设置用于imshow AxesImage的所有后续渲染。由于最初的plt.imshow
使用全零数据,因此vmin
和vmax
都设置为0(初始数据的最小值和最大值)。这使得 all 值显示为相同的颜色。因此,要阻止这种情况发生,请自己提供vmin
和vmax
。 - Use
repeat=False
to stop the animation after 200 frames. - Set
vmin=0, vmax=1
in the initial call toimshow
. The initial call toplt.imshow
setsvmin
andvmax
, which governs the correspondence between values and colors. That setting is used for all subsequent renderings of the imshow AxesImage. Since the initialplt.imshow
uses all-zero data,vmin
andvmax
both get set to 0 (the min and max of the initial data). That makes all values show up as the same color. So to stop that from happening, supply thevmin
andvmax
yourself.
这篇关于使用Matplotlib在Python中动画兰登的蚂蚁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!