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.
The syntax is as below:
scipy.interpolate.griddata(points, values, xi, method='linear',
fill_value=nan, rescale=False)
points
means the randomly generated data points.
values
are data points generated using a function.
xi
are the grid data points to be used when interpolating.
method
means the method of interpolation. It can be cubic
, linear
or nearest
.
The fill_value
, which defaults to nan
if the specified points are out of range. However, for nearest
, it has no effect.
rescale
is useful when some points generated might be extremely large. In that case, it is set to True
.
The function returns an array of interpolated values in a grid.
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')
Here is a line-by-line explanation of the code above:
values
later in line 19.griddata
method, over different grids, specifying different method
parameters.griddata
visualizations.