How to use the scipy.interpolate.interp1d() method
Overview
Suppose you have and values, and want to use these values to create a linear function where . This function can be used to interpolate unknown values given values.
In this shot, we’ll examine how to use the scipy.interpolate.interp1d() method to estimate data points of a line by creating a function that already uses two known x and y values.
The interp1d means interpolating on a 1 dimension, as in a line, with x and y axes only.
Syntax
scipy.interpolate.interp1d(x, y, kind = 'linear', axis = - 1, copy = True,
bounds_error = None, fill_value = nan, assume_sorted = False)
Parameters
-
The
xandyvalues are arguments that should be specified when calling this method, but the rest are optional, with the default values as specified. -
The
kindparameter specifies the type of curve you want. This parameter can bequadratic,cubic, or any other type but the default islinear. -
The
axisspecifies the axis along which to interpolate, the default beingy. -
The
copyparameter makes a copy ofxandyfirst ifTrueor just referencesxandyifFalse. -
The
bounds_errorparameter raises an error every time you try to interpolate an out-of-range value. The error will be ignored if extrapolate is specified in thefill_valueparameter. -
The
fill_valueisNaNby default andNaNvalues are generated every time you try to interpolateyvalues out of range unlessextrapolateis specified. -
The
assume_sortedparameter makes sure thatxvalues are sorted. IfTrue,xvalues will be values that are increasing.
Return function
The method returns a function, that can now be used to interpolate y data points.
Example
import matplotlib.pyplot as pltimport numpy as npimport scipyfrom scipy.interpolate import interp1dx = np.arange(10,20)print('x:',x)y = np.exp(-x/10)print('y:',y)f_linear = scipy.interpolate.interp1d(x,y)xnew = np.arange(10,19,0.1)ynew = f_linear(xnew)print('new_x:',xnew)print('new_y:',ynew)plt.scatter(x, y, color = 'blue')plt.plot(xnew, ynew, color = 'black')plt.xlabel("X")plt.ylabel("Y")plt.title("1d Interpolation using scipy interp1d method")plt.show()plt.savefig('output/graph.png')
Code explanation
- Lines
1to5import the necessary modules. - Line
8generates random points forxusing numpy. - Line
13generates random points foryusing numpy. - Line
19creates the linear function for interpolation. - Line
22generates new randomxpoints. - Line
25interpolates newypoints using the linear function generated earlier. - Lines
10,15,27,28print out the points generated. - Lines
32and35plots out scatter and line plots of the points on a graph. - Lines
38,41and45labels thexandyaxes as well as the graph itself. - Lines
48and51display the graph and saves it respectively.