Plot a line from discrete data with extrapolated jumps

Aim: connect discrete data points sampling a function with jumps in a nice way.


In [1]:
import numpy as np

import matplotlib.pyplot as plt
%matplotlib inline

%load_ext autoreload
%autoreload 2

In [2]:
def jumpify(x, y, threshold=1.0):
    """Add extrapolated intermediate point at position of jumps"""
    oldx, oldy = np.asarray(x), np.asarray(y)
    for ind in np.where(np.abs(np.diff(oldy)) > threshold)[0]:
        newx = list(oldx[:ind+1])
        midx = 0.5*(oldx[ind]+oldx[ind+1])
        newx.extend([midx, midx])
        newx.extend(oldx[ind+1:])
        newy = list(oldy[:ind+1])
        newy.extend([1.5*oldy[ind]-0.5*oldy[ind-1], 1.5*oldy[ind+1]-0.5*oldy[ind+2]])
        newy.extend(oldy[ind+1:])
        oldx, oldy = newx, newy
    return oldx, oldy

Example usage


In [3]:
def f(x):
    return np.where(x < 0.5, x, x + 0.5)
x = np.linspace(0, 1, 10)
plt.plot(x, f(x), 'bo-', label='sampling points with connecting line')
newx, newy = jumpify(x, f(x), threshold=0.2)
plt.plot(newx, newy, 'g-', label='jumpified line')
plt.legend(loc='lower center', bbox_to_anchor=(0.5, 1.0))


Out[3]:
<matplotlib.legend.Legend at 0x7f7b4fd4c610>