# Smoothing results from scipy griddata interpolatioin

I am using the griddata interpolation package in scipy, and an extrapolation function pulled from fatiando:

``````import numpy as np
import scipy
from scipy.interpolate import griddata
import matplotlib.pyplot as plt

def extrapolate_nans(x, y, v):
'''
Extrapolate the NaNs or masked values in a grid INPLACE using nearest
value.

.. warning:: Replaces the NaN or masked values of the original array!

Parameters:

* x, y : 1D arrays
Arrays with the x and y coordinates of the data points.
* v : 1D array
Array with the scalar value assigned to the data points.

Returns:

* v : 1D array
The array with NaNs or masked values extrapolated.
'''

else:
nans = np.isnan(v)
notnans = np.logical_not(nans)
v[nans] = scipy.interpolate.griddata((x[notnans], y[notnans]), v[notnans],
(x[nans], y[nans]), method='nearest').ravel()
return v

grid_x, grid_y = np.mgrid[0:1.5:50j, 0:1.2:50j]
points = np.random.rand(50, 2)
values = np.random.random_integers(1,10,50)

x = []
y = []
for i in points:
x.append(i[0])
y.append(i[1])
n = plt.Normalize(values.min(), values.max())

grid_z = griddata(points, values, (grid_x, grid_y), method='cubic')
extrapolate_nans(grid_x,grid_y,grid_z)
plt.contourf(grid_x,grid_y,grid_z)
plt.scatter(x,y,c=values)
plt.colorbar()

plt.show()
``````

I think the results are decent, but the problem is that the extrapolated values have a distinct zigzag pattern:

How do I smooth these lines? Or is there an alternative interpolation method in python that will generate smoother results?

• For smoothing per se you probably need another algorithm, but have you tried out "linear" and "cubic" interpolation instead of "nearest"? – Curlew Feb 5 '14 at 18:27
• I would like to suggest you do not want to smooth these lines: their pattern is purely an artifact of the interpolation method and reflects almost nothing meaningful about the data. It is better to mask out the areas beyond the extent of your data. – whuber Feb 5 '14 at 18:56
• This look like a rounding issue. Have you tried forcing all your values to be float ? – radouxju Feb 5 '14 at 19:39
• @Curlew the problem is I don't know how to extrapolate a "cubic" or "linear" model in scipy, hence the need to use "nearest outside of the bounds – camdenl Feb 5 '14 at 19:45
• @whuber I understand that these values are meaningless, I'd just like my image to look a little bit better, just a little lying around the edges :p – camdenl Feb 5 '14 at 19:46