下面是一个完全有效的代码,它为具有周期性边界的单车道道路设置动画。现在我想为两条甚至更多的车道设置动画。我有一个工作代码,其中位置向量现在是一个矩阵,每列代表一个车道。由此,我可以创建另一个 theta 向量,我希望在动画中的第一个向量之外显示它(通过将半径设置得更大一点)。我试图将矩阵(theta 和 r)放在 ax.scatter(theta, r, c=color) 中,但这不起作用。有人对如何解决这个问题有建议吗?我可以使用 matplotlib 的动画以外的其他东西,但由于它对单车道问题工作得很好,所以对我来说是最简单的。
把它包起来。如何同时为两个或多个矢量设置动画?例如,如果我有 r1、r2 和 theta1、theta2 并且想要每次都“绘制”它们,而不是像代码中那样只有 r 和 theta。
非常感谢您的帮助。
import numpy as np
from numpy.random import random as rnd
import matplotlib.pyplot as plt
from matplotlib import animation
roadlength = 50
numcars = 10
numframes = 1000 #Time
v_max = 5
p = 0.5
positions = np.zeros(numcars)
velocities = np.zeros(numcars)
theta = np.zeros(numcars)
color = np.linspace(0,numcars-1,numcars)
#Initiate r so roadlength = circumference of one lap
r = []
for i in range(numcars):
r.append(roadlength/(2*np.pi))
#Initiate positions so the cars are spread out over the road
for i in range(1,numcars):
positions[i] = positions[i-1] + (roadlength/numcars)
#Create figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='polar')
ax.axis('off')
#Update positions, animate function runs framenr times
def animate(framenr):
positions_tmp = np.array(positions, copy=True)
#Update position and velocity for each car
for i in range(numcars):
#Increase velocity if below max
if velocities[i] < v_max:
velocities[i] += 1
#Decrease velocity if car in front is close
d = positions_tmp[(i+1)%numcars] - positions_tmp[i]
if d <= 0:
d += roadlength
if velocities[i] >= d:
velocities[i] = d-1
#Decrease velocity randomly
if velocities[i] > 0:
if rnd() < p:
velocities[i] -= 1
positions[i] = positions_tmp[i] + velocities[i]
theta[i] = positions[i]*2*np.pi/roadlength
return ax.scatter(theta, r, c=color),
# Call the animator, blit=True means only re-draw parts that have changed
anim = animation.FuncAnimation(fig, animate, frames=numframes, interval=100, blit=True, repeat=False)
plt.show()