如何在 matplotlib 中围绕一组点绘制虚线 "cone" 的恒定斜率?

How to plot a dashed "cone" of constant slope around a set of points in matplotlib?

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

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

然后根据需要进行反映。我想要做的是在每个点周围绘制 "cone of uncertainty"、[-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()

我希望添加视锥细胞后的情节看起来像这样:

我也将把它包括在一篇论文中,所以任何美化技巧都会受到赞赏。

编辑:解决了,意识到我只需要单独绘制圆锥部分。

您可以为数据中的每个点绘制由圆锥体组成的两条线

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