如何在matplotlib的一组点周围绘制一个恒定斜率的虚线“圆锥”?

时间:2016-11-05 15:04:57

标签: python matplotlib random-walk

我有一些python代码,我用它来创建随机游走的图。步行将反映[-a,a]的障碍。序列中的后续值由

生成
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 个答案:

答案 0 :(得分: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