How do I interpolate a 2D gridded point cloud to a continuous area?

天涯浪子 提交于 2019-12-05 09:33:13
ImportanceOfBeingErnest

tricontourf

You might use a tricontour / tricontourf plot of the valid values. To this end, you first need to filter out all nan values (you should indeed make the invalid values np.nan instead of None). Those values, together with their coordinates can be put into plt.tricontourf() to obtain a contour plot without the need of manual interpolation.

import matplotlib.pyplot as plt
import numpy as np

# Generate some example data
f = lambda x,y : np.exp((-(x-150)**2-(y-150)**2)/3.e3)
plotGrid = np.zeros((300,300))*np.nan
coo = np.random.randint(5,295, size=(150,2) )
for x,y in coo:
    plotGrid[y,x] = f(x,y)
#plotGrid is now a numpy.ndarray with shape (300,300), mostly np.nan, and dtype float

# filter out nan values and get coordinates.
x,y = np.indices(plotGrid.shape)
x,y,z = x[~np.isnan(plotGrid)], y[~np.isnan(plotGrid)], plotGrid[~np.isnan(plotGrid)]

plt.tricontourf(x,y,z)

plt.colorbar()
plt.show()

tripcolor

Using tripcolor is another option then:

plt.tripcolor(x,y,z, shading='gouraud')

interpolate and contourf

You can also interpolate the data on a grid first, using matplotlib.mlab.griddata, and then either use a normal contourf plot,

xi = np.linspace(0, plotGrid.shape[1], plotGrid.shape[1])
yi = np.linspace(0, plotGrid.shape[0], plotGrid.shape[0])
zi = mlab.griddata(x, y, z, xi, yi, interp='linear')
plt.contourf(xi, yi, zi, 15)

interpolate and imshow

Or in the same manner use an imshow plot,

plt.imshow(zi)

I think scipy.interpolate.interp2d does what you need:

import scipy.interpolate

z_all = plotGrid.astype(float)            # convert nones to nan
x_all, y_all = np.indices(plotGrid.shape) # get x and y coordinates

# convert to 1d arrays of coordinates
valid = ~np.isnan(z_all)
x, y, z = x_all[valid], y_all[valid], z_all[valid]

# interpolate
interp = scipy.interpolate.interp2d(x, y, z)
filled_data = interp(x_all[:,0], y_all[0,:])  # this is kinda gross, but `interp` doesn't
                                              # do normal broadcasting

plt.imshow(filled_data)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!