不规则空间数据的等高线图

不规则空间数据在规则网格上插值的等高线图与非结构三角形网格的三棱图的比较。

由于 contourcontourf 期望数据存在于规则网格上,因此绘制不规则间隔数据的等高线图需要不同的方法。这两个选项是:

  • 首先将数据插值到常规网格。这可以通过机载装置完成,例如,通过LinearTriInterpolator或使用外部功能,例如 通过scipy.interpolate.griddata。然后用常规的等高线绘制插值数据。
  • 直接使用tricontourtricontourf,它将在内部进行三角测量。

此示例显示了两种方法。

  1. import matplotlib.pyplot as plt
  2. import matplotlib.tri as tri
  3. import numpy as np
  4. np.random.seed(19680801)
  5. npts = 200
  6. ngridx = 100
  7. ngridy = 200
  8. x = np.random.uniform(-2, 2, npts)
  9. y = np.random.uniform(-2, 2, npts)
  10. z = x * np.exp(-x**2 - y**2)
  11. fig, (ax1, ax2) = plt.subplots(nrows=2)
  12. # -----------------------
  13. # Interpolation on a grid
  14. # -----------------------
  15. # A contour plot of irregularly spaced data coordinates
  16. # via interpolation on a grid.
  17. # Create grid values first.
  18. xi = np.linspace(-2.1, 2.1, ngridx)
  19. yi = np.linspace(-2.1, 2.1, ngridy)
  20. # Perform linear interpolation of the data (x,y)
  21. # on a grid defined by (xi,yi)
  22. triang = tri.Triangulation(x, y)
  23. interpolator = tri.LinearTriInterpolator(triang, z)
  24. Xi, Yi = np.meshgrid(xi, yi)
  25. zi = interpolator(Xi, Yi)
  26. # Note that scipy.interpolate provides means to interpolate data on a grid
  27. # as well. The following would be an alternative to the four lines above:
  28. #from scipy.interpolate import griddata
  29. #zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear')
  30. ax1.contour(xi, yi, zi, levels=14, linewidths=0.5, colors='k')
  31. cntr1 = ax1.contourf(xi, yi, zi, levels=14, cmap="RdBu_r")
  32. fig.colorbar(cntr1, ax=ax1)
  33. ax1.plot(x, y, 'ko', ms=3)
  34. ax1.axis((-2, 2, -2, 2))
  35. ax1.set_title('grid and contour (%d points, %d grid points)' %
  36. (npts, ngridx * ngridy))
  37. # ----------
  38. # Tricontour
  39. # ----------
  40. # Directly supply the unordered, irregularly spaced coordinates
  41. # to tricontour.
  42. ax2.tricontour(x, y, z, levels=14, linewidths=0.5, colors='k')
  43. cntr2 = ax2.tricontourf(x, y, z, levels=14, cmap="RdBu_r")
  44. fig.colorbar(cntr2, ax=ax2)
  45. ax2.plot(x, y, 'ko', ms=3)
  46. ax2.axis((-2, 2, -2, 2))
  47. ax2.set_title('tricontour (%d points)' % npts)
  48. plt.subplots_adjust(hspace=0.5)
  49. plt.show()

不规则空间数据的等高线图例

参考

此示例中显示了以下函数和方法的用法:

  1. import matplotlib
  2. matplotlib.axes.Axes.contour
  3. matplotlib.pyplot.contour
  4. matplotlib.axes.Axes.contourf
  5. matplotlib.pyplot.contourf
  6. matplotlib.axes.Axes.tricontour
  7. matplotlib.pyplot.tricontour
  8. matplotlib.axes.Axes.tricontourf
  9. matplotlib.pyplot.tricontourf

下载这个示例