2017-05-05 98 views
0

我被一小段使用matplotlib的代碼困在python中,想要一些幫助。我試圖在python中使用matplotlib包在Python中動畫兩個盒子汽車,但我無法獲得animate函數來同時更新兩個汽車的x座標。在matplotlib中爲funcAnimation添加參數

的最小工作示例下面給出:

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() 

但我想要的東西像下面。 Python在運行此代碼時崩潰。

def animate(x1,x2): 
    rect_l.set_x(x1) 
    rect_h.set_x(x2) 
    return rect_l,rect_h, 


plt.axis([0, maxL, -10, 10]) 
plt.xlabel('time (s)') 
plt.ylabel('road') 
plt.title('Car simulation') 
ani = animation.FuncAnimation(fig1, animate, (lead[:,0],host[:,0]), init_func = init, interval=0.1, blit=False) 

plt.show() 

回答

1

取而代之的是價值的使用用於繪圖,您可以提供的幀數到frames說法。

ani = animation.FuncAnimation(fig1, animate, frames=len(lead)) 

這相當於使用0len(lead)之間的範圍內的,並且將調用與當期的幀的整數的動畫。 您可以使用此編號從動畫功能中的leadhost數組中選擇適當的值。

def animate(i): 
    x1 = lead[i,0] 
    x2 = host[i,0] 
    rect_l.set_x(x1) 
    rect_h.set_x(x2) 
+0

謝謝。這樣可行。 – shunyo

相關問題