简体   繁体   中英

Python - interpolating/pcolor unevenly spaced numpy matrix

I currently have aa roughly 100x120 2d numpy matrix. The indices refer to "coordinates" and the value in the matrix is the "height" I'm trying to plot this data using pcolor similar to the "Two dimensional spline representation" shown here:

http://docs.scipy.org/doc/scipy-0.7.x/reference/tutorial/interpolate.html

My issue is that though all my "coordinates" and "heights" are whole numbers, the coordinates are not evenly space. For example,only specific rows contain data (not equal spacing), and each row that contains data will only have a "height" value for every other entry (same spacing for each row that has data). A simple example of what I mean is as follows:

[[nan,   3, nan,   1, nan,   2], 
 [nan, nan, nan, nan, nan, nan],
 [nan,   5, nan,   2, nan,   3],
 [nan, nan, nan, nan, nan, nan],
 [nan, nan, nan, nan, nan, nan],
 [nan, nan, nan, nan, nan, nan],
 [nan,   4, nan,   1, nan,   2]]

I have been trying to follow the interpolation/pcolor example I linked to, but have been unsuccessful. My goal is to have a nice continous pcolor type plot over all my data, interpolating between points with data to fill in those nans.

I would appreciate any assistance you can offer.

What's the problem? You just need to extract the indexes of the cells with values and pass those to the interpolate function with the 'height' values. There's some code that does this below.

import numpy as np
from numpy import nan
from scipy import interpolate
import matplotlib.pyplot as plt

a = np.array([[nan,   3, nan,   1, nan,   2], 
 [nan, nan, nan, nan, nan, nan],
 [nan,   5, nan,   2, nan,   3],
 [nan, nan, nan, nan, nan, nan],
 [nan, nan, nan, nan, nan, nan],
 [nan, nan, nan, nan, nan, nan],
 [nan,   4, nan,   1, nan,   2]])

x, y = np.where(np.isfinite(a))
z = a[x,y]

xnew,ynew = np.mgrid[0:6:70j,0:6:70j]
tck = interpolate.bisplrep(x,y,z,s=0, kx=1, ky=1)
znew = interpolate.bisplev(xnew[:,0],ynew[0,:],tck)

plt.figure()
plt.pcolor(xnew,ynew,znew)
plt.colorbar()
plt.title("Interpolated function.")
plt.show()

The result will look something this:

在此输入图像描述

Note that this doesn't match the exact orientation of your matrix. To do so you would have to change the origin of the plot to be in the top left corner and possibly transpose the data. I'll leave that as an exercise to you.

Also, the method of getting the indexes of the non-na values is a little crude, so perhaps someone else could comment on that (thanks to seberg for the tip).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM