Python 向matplotlib中的funcAnimation添加参数
我一直在使用python中的matplotlib编写一小段代码,希望得到一些帮助。我正在尝试使用python中的matplotlib包在python中为两辆厢式车设置动画,但我无法使用animate函数同时更新两辆车的x坐标 下面给出了一个简单的工作示例:Python 向matplotlib中的funcAnimation添加参数,python,matplotlib,Python,Matplotlib,我一直在使用python中的matplotlib编写一小段代码,希望得到一些帮助。我正在尝试使用python中的matplotlib包在python中为两辆厢式车设置动画,但我无法使用animate函数同时更新两辆车的x坐标 下面给出了一个简单的工作示例: import numpy as np import matplotlib.pyplot as plt import matplotlib.patches as patches import matplotlib.animation as an
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.animation as animation
# Complete length of trajectory
maxL = 2000
# Initial positions and velocities of lead and host cars
xl = 30
vl = 5
xh = 0
vh = 5
# Step size
dt = 0.1
lead = np.matrix([[xl,vl]])
host = np.matrix([[xh,vh]])
while xl < maxL:
xl = xl + vl*dt
lead = np.concatenate((lead,[[xl,vl]]), axis = 0)
xh = xh + vh*dt
host = np.concatenate((host,[[xh,vh]]), axis = 0)
road_width = 3;
fig1 = plt.figure(1)
ax = fig1.add_subplot(111)
rect_l = patches.Rectangle(
(lead[0,0], road_width/2), # (x,y)
10, # width
1, # height
facecolor = "red", # remove background
)
rect_h = patches.Rectangle(
(host[0,0], road_width/2), # (x,y)
10, # width
1, # height
facecolor = "blue", # remove background
)
ax.add_patch(rect_l)
ax.add_patch(rect_h)
def init():
plt.plot([0,maxL],[road_width,road_width],'k-')
plt.plot([0,maxL],[-road_width,-road_width],'k-')
plt.plot([0,maxL],[0,0],'k--')
return []
#### This works #####
def animate(x1):
rect_l.set_x(x1)
return rect_l,
plt.axis([0, maxL, -10, 10])
plt.xlabel('time (s)')
plt.ylabel('road')
plt.title('Car simulation')
ani = animation.FuncAnimation(fig1, animate, lead[:,0], init_func = init, interval=0.1, blit=False)
plt.show()
您可以为frames参数提供帧数,而不是用于打印的值
ani = animation.FuncAnimation(fig1, animate, frames=len(lead) )
这相当于使用介于0和lenlead之间的范围,并将使用当前帧的整数调用动画。
可以使用此数字从动画函数中的导程和主机阵列中选择适当的值
def animate(i):
x1 = lead[i,0]
x2 = host[i,0]
rect_l.set_x(x1)
rect_h.set_x(x2)
def animate(i):
x1 = lead[i,0]
x2 = host[i,0]
rect_l.set_x(x1)
rect_h.set_x(x2)