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

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


    * 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.


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

    if np.ma.is_masked(v):
        nans = v.mask
        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:
n = plt.Normalize(values.min(), values.max())

grid_z = griddata(points, values, (grid_x, grid_y), method='cubic')


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

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, 2014 at 18:27
  • 1
    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, 2014 at 18:56
  • This look like a rounding issue. Have you tried forcing all your values to be float ?
    – radouxju
    Feb 5, 2014 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 Feb 5, 2014 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 Feb 5, 2014 at 19:46


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.