2016-11-05 48 views
0

我有一些Python代碼用於創建隨機遊走的情節。步行將反映[-a,a]的障礙。序列中的隨後的值是由如何繪製matplotlib中一組點周圍的恆定斜率的虛線「圓錐體」?

r[n] = r[n-1] + Uni[-R, R] 

,然後將其反映爲必要生成。我想要做的是繪製每個點周圍的「不確定性錐」,[-R, R]

這裏是Python代碼到目前爲止我有:

import matplotlib.pyplot as plt 
import random 

uni = random.uniform 

t = [] 
r = [] 

r0 = .15 # Seed for our random walk. Can be between -a and a 
a = .2 # Distance of barriers from 0. Should be in (0, 1] 
R = .04 # Height of half-cone in r-direction 
dt = 20 # Sample period 
N = 20 # Number of samples 

cone_ls = ':' 
cone_clr = 'blue'#[0, .5, .5] 

for i in range(N): 
    t.append(i*dt) 
    if i == 0: 
     r.append(r0) 
    else: 
     ''' 
     When our cone of uncertainty outpaces out barriers, 
     simply sample uniformly inside the barriers. 
     ''' 
     if(R > 2*a): 
      r.append(uni(-a, a)) 
      continue 
     rn = r[i - 1] + uni(-R, R) 
     ''' 
     If the sampled value comes above the upper barrier, 
     reflect it back below. 
     ''' 
     if(rn > a): 
      r.append(2*a - rn) 
      continue 
     ''' 
     If the sampled value comes below the lower barrier, 
     reflect it back above. 
     ''' 
     if(rn < -a): 
      r.append(-2*a - rn) 
      continue 
     ''' 
     Otherwise just append the sampled value. 
     ''' 
     r.append(rn) 
# Plot cones 
for i, pt in enumerate(r): 
    plt.plot([t[i], t[i] + dt], [pt, pt + R], linestyle=cone_ls, color=cone_clr, linewidth=2) 
    plt.plot([t[i], t[i] + dt], [pt, pt - R], linestyle=cone_ls, color=cone_clr, linewidth=2) 

plt.plot(t, r, 'ro') 
plt.plot(t, [a]*N) 
plt.plot(t, [-a]*N) 
plt.axis([min(t), max(t), -2*a, 2*a]) 
plt.xlabel('Time (min)') 
plt.ylabel('Relative Difference, r') 
plt.show() 

我想情節看起來像這樣添加錐後:

random walk with cones

我也將包括在一個文件中,所以任何美化技巧值得讚賞。

編輯:解決,實現我只需要繪製錐形部分單獨。

回答

1

你可以只繪製兩條線錐組成的每一個點在你的數據

for i in range(N): 
    plt.plot([t[i]+dt,t[i],t[i]+dt],[r[i]-R,r[i],r[i]+R], color="#808080") 

最後,你還需要設置x限制max(t)+dt
plt.axis([min(t), max(t)+dt, -2*a, 2*a])

enter image description here

+0

在我意識到和你一樣意識到這只是另一組情節之後,我最終做了一些稍微複雜的事情。這一行很簡潔,謝謝! – ijustlovemath