1

I have a list of points:

pointList = [ [x1,y1,z1], [x2,y2,z2], ... [xn,yn,zn]]

and I want to draw a contour plot of this set of points.

I try:

import matplotlib.pyplot as plt
pointList = [ [x1,y1,z1], [x2,y2,z2], ... [xn,yn,zn]]
x = [el[0] for el in pointList]
y = [el[1] for el in pointList]
z = [el[2] for el in pointList]
plt.contourf(x,y,z)
plt.show()

but I have this exception:

TypeError: Input z must be a 2D array.

This is strange because in the documentation of matplotlib I find:

Call signatures:
contour(Z)
make a contour plot of an array Z. The level values are chosen automatically.
contour(X,Y,Z)
X, Y specify the (x, y) coordinates of the surface

So I don't understand why it fails ...

McGrady
  • 10,869
  • 13
  • 47
  • 69
rudy
  • 176
  • 3
  • 14
  • Do your points actually create a surface? `X` and `Y` are the unique `x` and `y` values to use for the surface. It's not intended to be used for scattered data – Suever Apr 13 '17 at 15:14
  • not sure to understand. how should I do to "actually" create a surface? – rudy Apr 13 '17 at 15:16
  • 4
    Possible duplicate of [Make contour of scatter](http://stackoverflow.com/questions/18764814/make-contour-of-scatter) – Suever Apr 13 '17 at 15:19
  • You have scattered data (it seems) so you'll need to convert it to a regular grid using the method in the duplicate – Suever Apr 13 '17 at 15:19

1 Answers1

2

In either case, contour(Z), or contour(X,Y,Z), the input Z must be a 2D array.

If your data does not live on a grid, you either need to interpolate it to a grid or you cannot use contour.

An easy alternative is to use tricontour.

import matplotlib.pyplot as plt
import numpy as np
pointList = [ [x1,y1,z1], [x2,y2,z2], ... [xn,yn,zn]]
pointList = np.array(pointList)
plt.tricontour(pointList[:,0],pointList[:,1],pointList[:,2])
plt.show()

There is a good example which compares tricontour with a contour of interpolated data: tricontour_vs_griddata.

You may also look at:

Community
  • 1
  • 1
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712