如何使用matplotlib设置二维栅格的动画

2024-10-06 07:35:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用python编写langton的ant代码,当我将其作为ASCII“模拟”进行测试时,代码确实可以工作,但在matplotlib中将其作为2d动画工作时遇到了问题。我从来没有真正弄乱过matplotlib,但我试图通过这样做来学习

import datetime,pprint,keyboard,time,os
from matplotlib import pyplot as plt
from matplotlib import animation

antLocation = (15,15) # (y,x)
antDirection = 270
grid = [[0 for i in range(30)].copy() for _ in range(30)]

def update(data):
    global grid
    global antLocation
    global antDirection
    if(grid[antLocation[0]][antLocation[1]] == 0):
        antDirection +=90
        grid[antLocation[0]][antLocation[1]] = 1
    else:
        antDirection -=90
        grid[antLocation[0]][antLocation[1]] = 0
    if (antDirection == 0 or antDirection == 360): #UP
        antLocation = (antLocation[0]-1, antLocation[1])
        antDirection = 0
    elif (antDirection == 90): #RIGHT
        antLocation = (antLocation[0], antLocation[1] + 1)
    elif (antDirection == 180): # DOWN
        antLocation = (antLocation[0]+1, antLocation[1])
    else: #(antDirection == 270 or antDirection == -90): #LEFT
        antLocation = (antLocation[0], antLocation[1] - 1)
        antDirection = 270
    mat.set_data(grid)
    return [mat]
    
fig,ax = plt.subplots()
mat = ax.matshow(grid)
ani = animation.FuncAnimation(fig, update)
plt.show()

Tags: 代码infromimportformatplotlibupdaterange
1条回答
网友
1楼 · 发布于 2024-10-06 07:35:26

您需要一个函数来创建各个帧(对于每个时间点t)。然后将此函数传递给animation.FuncAnimation()。由于您使用的是全局变量,update()不需要返回任何内容

from matplotlib import pyplot as plt
from matplotlib import animation

antLocation = (15,15) # (y,x)
antDirection = 270
grid = [[0 for i in range(30)].copy() for _ in range(30)]

def update(data):
    global grid
    global antLocation
    global antDirection
    if(grid[antLocation[0]][antLocation[1]] == 0):
        antDirection +=90
        grid[antLocation[0]][antLocation[1]] = 1
    else:
        antDirection -=90
        grid[antLocation[0]][antLocation[1]] = 0
    if (antDirection == 0 or antDirection == 360): #UP
        antLocation = (antLocation[0]-1, antLocation[1])
        antDirection = 0
    elif (antDirection == 90): #RIGHT
        antLocation = (antLocation[0], antLocation[1] + 1)
    elif (antDirection == 180): # DOWN
        antLocation = (antLocation[0]+1, antLocation[1])
    else: #(antDirection == 270 or antDirection == -90): #LEFT
        antLocation = (antLocation[0], antLocation[1] - 1)
        antDirection = 270
    
def frame(t):
    """
    Update the grid and return a plot of the earlier grid.
    t (time) is not used, but necessary to be able to pass
    this function to matplotlib.animation.FuncAnimation.
    """
    plt.cla()
    image = plt.imshow(grid, cmap='Greys')
    update(grid)
    return image

fig, ax = plt.subplots()
ani = animation.FuncAnimation(fig, frame)
plt.show()

相关问题 更多 >