How to plot line (polygonal chain) with numpy/scipy/matplotlib with minimal smoothing

Solution 1:

For that type of graph, you want monotonic interpolation. The PchipInterpolator class (which you can refer to by its shorter alias pchip) in scipy.interpolate can be used:

import numpy as np
from scipy.interpolate import pchip
import matplotlib.pyplot as plt


# Data to be interpolated.
x = np.arange(10.0)
y = np.array([5.0, 10.0, 20.0, 15.0, 13.0, 22.0, 20.0, 15.0, 12.0, 16.0])

# Create the interpolator.
interp = pchip(x, y)

# Dense x for the smooth curve.
xx = np.linspace(0, 9.0, 101)

# Plot it all.
plt.plot(xx, interp(xx))
plt.plot(x, y, 'bo')
plt.ylim(0, 25)
plt.grid(True)
plt.show()

Result:

enter image description here

Solution 2:

The problem is not a display problem. It is an interpolation problem. You are interpolating using spline functions. Picking the right interpolation method is very much depending on the kind of data you have. You cannont expect to have an interpolation function which will behave right in every circumstances (the interpolation have no way to know that your function is increasing).

Solution 3:

You should either look at

scipy.interpolate.LSQUnivariateSpline and play with k parameter (degree of the spline)

or scipy.interpolate.UnivariateSpline and play with k and s parameter.