How to use the scipy.interpolate.griddata() method
Overview
Scipy is a Python library useful for scientific computing. It contains numerous modules, including the interpolate module, which is helpful when it comes to interpolating data points in different dimensions whether one-dimension as in a line or two-dimension as in a grid.
The scipy.interpolate.griddata() method is used to interpolate on a 2-Dimension grid.
Syntax
The syntax is as below:
scipy.interpolate.griddata(points, values, xi, method='linear',
fill_value=nan, rescale=False)
Parameters
-
pointsmeans the randomly generated data points. -
valuesare data points generated using a function. -
xiare the grid data points to be used when interpolating. -
methodmeans the method of interpolation. It can becubic,linearornearest. -
The
fill_value, which defaults tonanif the specified points are out of range. However, fornearest, it has no effect. -
rescaleis useful when some points generated might be extremely large. In that case, it is set toTrue.
Return value
The function returns an array of interpolated values in a grid.
Code
import numpy as npimport matplotlib.pyplot as pltimport scipyfrom scipy.interpolate import griddata#define a functiondef func(x,y):return (x**2+y**2+(x*y)**2)**2#generate grid data using mgridgrid_x,grid_y = np.mgrid[0:1:1000j, 0:1:2000j]#generate random pointsrng = np.random.default_rng()points = rng.random((1000, 2))#generate values from the points generated abovevalues = func(points[:,0], points[:,1])#generate grid data using the points and values abovegrid_a = griddata(points, values, (grid_x, grid_y), method='cubic')grid_b = griddata(points, values, (grid_x, grid_y), method='linear')grid_c = griddata(points, values, (grid_x, grid_y), method='nearest')#visualizationsfig, axs = plt.subplots(2, 2)axs[0, 0].plot(func(grid_x,grid_y))axs[0, 0].set_title("main")axs[1, 0].plot(grid_a)axs[1, 0].set_title("cubic")axs[0, 1].plot(grid_b)axs[0, 1].set_title("linear")axs[1, 1].plot(grid_c)axs[1, 1].set_title("nearest")fig.tight_layout()plt.savefig('output/graph.png')
Explanation
Here is a line-by-line explanation of the code above:
- Lines 1–4: We import the necessary modules.
- Lines 8 and 9: We define a function that will be used to generate
valueslater in line 19. - Line 12: We generate grid data and return a 2-D grid.
- Line 15: We initialize a generator object for generating random numbers.
- Line 16: We use the generator object in line 15 to generate 1000, 2-D arrays.
- Line 20: We generate values using the points in line 16 and the function defined in lines 8-9.
- Lines 23–27: We generate grid points using the
griddatamethod, over different grids, specifying differentmethodparameters. - Lines 31–42: We plot the different
griddatavisualizations.