use of contour and contourf

♀尐吖头ヾ 提交于 2019-12-11 06:19:35

问题


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 ...


回答1:


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:

  • Plotting Isolines/contours in matplotlib from (x, y, z) data set (which has an easy example for both, tricontour and interpolated contour)
  • matplotlib contour/contourf of **concave** non-gridded data (for the case that your data is concave)


来源:https://stackoverflow.com/questions/43395958/use-of-contour-and-contourf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!