matplotlib creating 2D arrays from 1D arrays - is

2020-06-25 05:26发布

问题:

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

回答1:

If your data is like the one you gave in the example, you already have a mesh (you have a value of z for each pair (x,y)) and you only need to reshape the arrays:

cols = np.unique(xs).shape[0]
X = xs.reshape(-1, cols)
Y = ys.reshape(-1, cols)
Z = zs.reshape(-1, cols)