I am trying to visualise some 3d data I have using matplotlibs contour plots, surface plots and wireframe plots.
my raw data is in the form of a numpy array with x,y and z each in their own column (e.g.):
| xs | ys | zs |
|---|---|----|
| 1 | 1 | 3 |
| 2 | 1 | 4 |
| 3 | 1 | 2 |
| 4 | 1 | 3 |
| 5 | 1 | 5 |
| 1 | 2 | -1 |
| 2 | 2 | -1 |
| 3 | 2 | -2 |
| 4 | 2 | 2 |
| 5 | 2 | 7 |
| 1 | 3 | 5 |
| 2 | 3 | 2 |
| 3 | 3 | 3 |
| 4 | 3 | 2 |
| 5 | 3 | 3 |
Now some of the plotting functions just take the data in 1D arrays corresponding to my columns (xs,ys,zs). However, some require a 2D array (meshgrid) format. Is there an easy way to convert from the 3 1D arrays to the correct format of 3 2D arrays? I have tried using numpy.meshgrid and, whilst this works for creating the X and Y 2D arrays, I can't work out a nice way to create the corresponding Z 2D array. I have managed to do it by making a blank 2D array and filling it with the appropriate values for Z, but this isn't very nice. Is there a better way to create the Z 2D array?
Below is my attempt (which works). Is there a way to make the Z array without cycling through both X and Y?
def getMeshGrid(dataArray):
"""get 2d coordinate grid and Z values in meshgrid format. requires values in
dataArray to have a rectangular region of x-y space covered uniformly"""
xs = dataArray[:,0]
ys = dataArray[:,1]
xmin,xmax = xs.min(), xs.max()
xstep = xs[xs!=xmin].min()-xmin
ymin,ymax = ys.min(), ys.max()
ystep = ys[ys!=ymin].min()-ymin
X = numpy.arange(xmin, xmax+xstep, xstep)
Y = numpy.arange(ymin, ymax+ystep, ystep)
X,Y = numpy.meshgrid(X,Y)
Z = numpy.zeros(X.shape)
height, width = X.shape
for i in range(0, height):
for j in range(0,width):
halfway = dataArray[dataArray[:,0]==X[i,j]] # finds all with that value of x
row = halfway[halfway[:,1]==Y[i,j]] # finds y value
Z[i,j] = row[0,6]
return X,Y,Z
Thanks in advance