python 动画移动方块

Animating moving square in python

我是 python 的 matplotlib 新手,我想制作一个在网格 space 上沿对角线移动的 1x1 正方形的动画。我写的这段代码几乎可以完成我想要它做的事情,但是矩形之前的位置仍然可见。

import matplotlib.pyplot as plt
import matplotlib.animation
import numpy as np

from matplotlib.patches import Rectangle


moving_block = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5]]

fig, ax = plt.subplots()

#set gridlines and lines every one unit
ax.grid(which='both')
ax.axis([0,5,0,5])


rectangle = Rectangle(moving_block[0], 1,1)
ax.add_patch(rectangle)

def animate(i):
    ax.add_patch(Rectangle(moving_block[i], 1,1))

ani = matplotlib.animation.FuncAnimation(fig, animate, 
                frames=len(moving_block), interval=300, repeat=True) 

plt.show()

如何只显示当前矩形?我应该使用这个 ax.add_patch(Rectangle) 函数以外的东西吗?

在函数“animate”的每次迭代中添加了清洁“ax”。 如果您对答案满意,请不要忘记为它投票:-)

import matplotlib.pyplot as plt
import matplotlib.animation
from matplotlib.patches import Rectangle

moving_block = [[0,0],[1,1],[2,2],[3,3],[4,4],[5,5]]

fig, ax = plt.subplots()
#set gridlines and lines every one unit
ax.grid(which='both')
ax.axis([0, 5, 0, 5])

rectangle = Rectangle(moving_block[0], 1,1)
ax.add_patch(rectangle)

def animate(i):
    ax.clear()
    ax.axis([0, 5, 0, 5])
    ax.grid(which='both')
    ax.add_patch(Rectangle(moving_block[i], 1,1))


ani = matplotlib.animation.FuncAnimation(fig, animate,
                frames=len(moving_block), interval=300, repeat=True)

plt.show()