5

I have 3D data as the columns of a numpy array (that is to say that array[0] = [0,0,0], etc.), e.g.

X     Y     Z

0     0     0
0     1     10
1     0     20
1     1     30

I would like to plot this so that each (X,Y) co-ordinate has a square centered on the co-ordinate, with a colorbar from (e.g.) 0 to 30 showing the Z value.

I would then like to overlay some contour lines, but the first part of the question is most important.

There is help for people who have already-gridded data, but I am not sure of the best matplotlib routine to call for my column data. Also, this is for scientific publication, so needs to be of a good quality and look! Hope someone can help!

user2970116
  • 85
  • 1
  • 6
  • 2
    Good question. You can try using `scipy.interpolate.interp2d` to create a function and resample onto a regular grid and then show the whole thing as an image. Another possibility may be to use `mayavi.mlab.triangular_mesh`, but for that you would need to create the triangles yourself using nearest neighbors or something. It is possible that mayavi actually has a simpler plotting function that already takes care of this. – eickenberg Nov 15 '14 at 22:37
  • 1
    It looks like your data is already defined on a rectilinear grid? – Oliver W. Nov 16 '14 at 01:27

1 Answers1

2

You can use griddata from matplotlib.mlab to grid your data properly.

import numpy as np
from matplotlib.mlab import griddata

x = np.array([0,0,1,1])
y = np.array([0,1,0,1])
z = np.array([0,10,20,30])
xi = np.arange(x.min(),x.max()+1)
yi = np.arange(y.min(),y.max()+1)
ar = griddata(x,y,z,xi,yi)

# ar is now
# array([[  0.,  20.],
#        [ 10.,  30.]])

The choice of the mapped xi and yi points is up to you, and they do not have to be integers as griddata can interpolate for you.

ebarr
  • 7,704
  • 1
  • 29
  • 40
  • seems griddata has been removed from newer matplotlib versions. – StanGeo Jun 11 '20 at 12:44
  • There is a replacement in `scipy.interpolate`: https://docs.scipy.org/doc/scipy/reference/generated/scipy.interpolate.griddata.html – Aant Jun 23 '20 at 08:54