我正在使用 Python 2.7 (Anaconda) 和 matplotlib 来获得“桌面”方形补丁 - 背景 - 上的方形补丁的动画,以便小方块必须沿着所需的方向移动(北、南、est、west)对于范围 = n 个位置(移动 = 1)。我第一次使用 FuncAnimation,但作为情节,我只得到绘制 n 次的正方形,而不是让它移动/动画。这是我的示例方向“南”的代码:
import matplotlib.pyplot as plt
import matplotlib.patches as ptc
from matplotlib import animation
import numpy as np
#__________________________________________________________________________PLOT
fig = plt.figure()
ax1 = fig.add_subplot(111,aspect='equal')
ax1.set_xlim((0,10))
ax1.set_ylim((0,10))
#________________________________________________FIGURES_VECTORS_INITIALIZATION
#DESK
desk=np.matrix([[1,1],[9,1],[9,9],[1,9]]) #desk vertices
#setting initialization - DESK
def initDesk():
ax1.add_patch(ptc.Polygon(desk, closed=True,
fill=False, hatch="/"))
#SQUARE
squVer=np.matrix([[4.5,6.5],[5.5,6.5],[5.5,7.5],[4.5,7.5]]) #square vertices
#_____________________________________________________DIRECTIONS_INITIALIZATION
move=1
null=0
#4DIRECTIONS
north=np.array(([+null,+move]))
south=np.array([+null,-move])
est=np.array([+move,+null])
west=np.array([-move,+null])
#_____________________________________________________________________ANIMATION
def animate(newPos):
iniSqu=np.matrix(squVer)
position=newPos
for step in range (0,4):
if step < 1: #starting point
newPos=iniSqu
else:
newPos=iniSqu+position
square=ptc.Polygon(newPos, closed=True,
facecolor="blue")
ax1.add_patch(square)
iniSqu=newPos
anim = animation.FuncAnimation(fig, animate(south),init_func=initDesk(),repeat=True)
plt.show()
关于什么可以解决问题并使补丁动画而不是在同一图形上绘制 n 次的建议?