Search code examples
python-3.xscipylinear-regressioninterpolationapproximation

Linear interpolation using scipy's interp1d


I am trying to do a linear interpolation

Code:

from scipy.interpolate import interp1d

x_ = [2.,   2.8, 16.7]
y_ = [0.87678869, 0.49044994, 1.4322675]
y_std = []
plt.plot(x_, y_, marker='o', color='k')
f = interp1d(x_, y_, kind='linear', bounds_error=False)

plt.plot(x_, f(x_), marker='o', color='tab:green')
plt.show()

enter image description here

I expected a linear line, but the result appears to be a piecewise fit. Could someone please suggest what's going wrong?


Solution

  • Interpolate just fills in the content between the points, and therefore it must hit every single point in your original dataset.

    What you're looking for is to run a linear regression:

    https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.linregress.html