ijustlovemath ijustlovemath - 1 month ago 12
Python Question

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

I have some python code I'm using to create plots of a random walk. The walk will reflect at the barriers of [-a,a]. The subsequent value in the sequence is generated by

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


which is then reflected as necessary. What I want to do is plot the "cone of uncertainty",
[-R, R]
around each point.

Here's the python code I've got so far:

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


I'd like the plot to look like this after adding the cones:

random walk with cones

I'm also going to be including this in a paper, so any beautifying tips are appreciated.

edit: solved, realized I just needed to plot the cone sections individually.

Answer

You can just plot the two lines the cone consists of for every point in your data

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

At the end, you also need to set the x limits to max(t)+dt
plt.axis([min(t), max(t)+dt, -2*a, 2*a])

enter image description here