2016-12-05 205 views
0

我在使用matplotlib繪製某些東西的路徑時遇到了一些麻煩。 這是我正在做的事情的基本版本。在python中使用matplotlib繪製軌跡

本質上,我看到該值是否在路徑中的任何點打破了某個閾值(在這種情況下爲6),然後再對它進行處理。

現在,我有3個列表設置。 end_vector將基於其他兩個列表。如果在單次模擬期間任何時候數值突破2,我會將對象的最後一個位置添加到我的end_vector

trajectories_vect是我想跟蹤所有5個模擬的軌跡,保留一個列表名單。我會在下面澄清。並且,timestep_vect存儲單個模擬的路徑。

from random import gauss 
from matplotlib import pyplot as plt 
import numpy as np 

starting_val = 5 
T = 1     #1 year 
delta_t = .1   #time-step 
N = int(T/delta_t)  #how many points on the path looked at 
trials = 5    #number of simulations 

#main iterative loop 
end_vect = [] 
trajectories_vect = [] 
for k in xrange(trials): 
    s_j = starting_val 
    timestep_vect = [] 
    for j in xrange(N-1): 
     xi = gauss(0,1.0) 
     s_j *= xi 
     timestep_vect.append(s_j) 
    trajectories_vect.append(timestep_vect) 
    if max(timestep_vect) > 5: 
     end_vect.append(timestep_vect[-1]) 
    else: 
     end_vect.append(0) 

好了,此時如果打印我的軌跡,我得到這樣的這一部分(我只發佈了兩個模擬,而不是完整的5):

[[ -3.61689976e+00 2.85839230e+00 -1.59673115e+00 6.22743522e-01 
1.95127718e-02 -1.72827152e-02 1.79295788e-02 4.26807446e-02 
-4.06175288e-02] [ 4.29119818e-01 4.50321728e-01 -7.62901016e-01 
-8.31124346e-02 -6.40330554e-03 1.28172906e-02 -1.91664737e-02 
-8.29173982e-03 4.03917926e-03]] 

這是好,什麼我想要發生。

現在,我的問題是,我不知道如何正確繪製我的路徑(y軸)與我的時間(x軸)。

首先,我想把我的數據放到numpy數組中,因爲我稍後需要使用它們來計算一些統計數據和其他來自numpy的經驗。

#creating numpy arrays from list 
#might need to use this with matplotlib somehow 
np_trajectories = np.array(trajectories_vect) 
time_array = np.arange(1,10) 

雖然這是問題的癥結所在。當我將軌跡(y軸)放入matplotlib中時,它不會將每個「列表」(row in numpy)視爲一條路徑。 5次模擬沒有獲得5次路徑,而是5次模擬得到9次路徑。我相信我輸入的東西是錯誤的,因此它以錯誤的方式使用了9個時間間隔。

#matplotlib stuff 
plt.plot(np_trajectories) 
plt.xlabel('timestep') 
plt.ylabel('trajectories') 
plt.show() 

這裏的圖像製作:

enter image description here

顯然,這是錯誤的,前面提到的原因。相反,我想在我的軌跡中有5個基於5個列表(行)的路徑。我似乎明白問題所在,但不知道如何解決問題。

在此先感謝您的幫助。

回答

2

當您撥打np_trajectories = np.array(trajectories_vect)時,軌跡列表將轉換爲2d numpy陣列。有關其尺寸的信息存儲在np_trajectories.shape中,在您的情況下,它是(5, 9)。因此,當您通過np_trajectoriesplt.plot()時,繪圖庫假定y值存儲在第一維中,而第二維描述要繪製的各條線。

就你而言,你所要做的就是轉置np_trajectories陣列。在numpy,它很簡單,只要

plt.plot(np_trajectories.T) 
plt.xlabel('timestep') 
plt.ylabel('trajectories') 
plt.show() 

如果你要繪製的x軸的時間,而不是一個步驟中,您必須確定您的時間進程列表或數組。在numpy,你可以這樣做

times = np.linspace(0, T, N-1) 
plt.plot(times, np_trajectories.T) 
plt.xlabel('timestep') 
plt.ylabel('trajectories') 
plt.show() 

產生如下圖所示: timesteps

+0

真棒,即做到了。非常感謝。 只需快速跟進。我如何確保我的x軸與我的時間步保持一致?我希望它能反映delta_t;即具有時間段1-9。而現在,這不是那麼做。 – DudeWah

+0

@DudeWah我已經更新了答案,其中包括將x軸繪製爲時間序列(我認爲是)您的情況。 –

+0

非常感謝您澄清一切! – DudeWah