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()
我想情节看起来像这样添加锥后:
我也将包括在一个文件中,所以任何美化技巧值得赞赏。
编辑:解决,实现我只需要绘制锥形部分单独。
在我意识到和你一样意识到这只是另一组情节之后,我最终做了一些稍微复杂的事情。这一行很简洁,谢谢! – ijustlovemath