[英]How can I animate a set of points with matplotlib?
I have an implemented Conway's Game of Life as: 我已经实施了康威的生命游戏:
def neighbors(point):
x, y = point
for i, j in itertools.product(range(-1, 2), repeat=2):
if any((i, j)):
yield (x + i, y + j)
def advance(board):
newstate = set()
recalc = board | set(itertools.chain(*map(neighbors, board)))
for point in recalc:
count = sum((neigh in board)
for neigh in neighbors(point))
if count == 3 or (count == 2 and point in board):
newstate.add(point)
return newstate
I want to visualize the result, so I tried to modify the given example from Matplotlib animation example : 我想要显示结果,所以我尝试从Matplotlib动画示例修改给定的示例 :
glider = set([(0, 0), (1, 0), (2, 0), (0, 1), (1, 2)])
fig, ax = plt.subplots()
x, y = zip(*glider)
mat, = ax.plot(x, y, 'o')
def animate(i):
glider = advance(glider)
x, y = zip(*glider)
mat.set_data(x, y)
return mat,
ani = animation.FuncAnimation(fig, animate, interval=50)
plt.show()
but that just plots the initial points . 但这只是绘制了初始点 。
The code you have should actually produce an error. 您拥有的代码实际上应该产生错误。 The problem is that you reference glider
before you assign it. 问题是在分配glider
之前参考glider
。
Mind the local scope of variables in python functions. 注意python函数中的局部变量范围。 Eg try 试试吧
a = 0
def f():
a = a + 1
f()
which will give you the same error. 哪个会给你同样的错误。
In your code of Conway's Game of Life, you can circumvent this by making glider
available to the global scope, global glider
. 在您的康威生命游戏代码中,您可以通过将glider
提供给全球范围的global glider
来规避这一点。 Also make sure your axes limits allow for the animation to be seen. 还要确保您的轴限制允许看到动画。
Complete example: 完整的例子:
import itertools
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def neighbors(point):
x, y = point
for i, j in itertools.product(range(-1, 2), repeat=2):
if any((i, j)):
yield (x + i, y + j)
def advance(board):
newstate = set()
recalc = board | set(itertools.chain(*map(neighbors, board)))
for point in recalc:
count = sum((neigh in board)
for neigh in neighbors(point))
if count == 3 or (count == 2 and point in board):
newstate.add(point)
return newstate
glider = set([(0, 0), (1, 0), (2, 0), (0, 1), (1, 2)])
fig, ax = plt.subplots()
x, y = zip(*glider)
mat, = ax.plot(x, y, 'o')
def animate(i):
global glider
glider = advance(glider)
x, y = zip(*glider)
mat.set_data(x, y)
return mat,
ax.axis([-15,5,-15,5])
ani = animation.FuncAnimation(fig, animate, interval=50)
plt.show()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.