pcolormesh

演示如何组合Normalization和Colormap实例以在pcolor()pcolormesh()imshow()类型图中绘制“级别”,其方式与contour / contourf的levels关键字参数类似。

  1. import matplotlib
  2. import matplotlib.pyplot as plt
  3. from matplotlib.colors import BoundaryNorm
  4. from matplotlib.ticker import MaxNLocator
  5. import numpy as np
  6. # make these smaller to increase the resolution
  7. dx, dy = 0.05, 0.05
  8. # generate 2 2d grids for the x & y bounds
  9. y, x = np.mgrid[slice(1, 5 + dy, dy),
  10. slice(1, 5 + dx, dx)]
  11. z = np.sin(x)**10 + np.cos(10 + y*x) * np.cos(x)
  12. # x and y are bounds, so z should be the value *inside* those bounds.
  13. # Therefore, remove the last value from the z array.
  14. z = z[:-1, :-1]
  15. levels = MaxNLocator(nbins=15).tick_values(z.min(), z.max())
  16. # pick the desired colormap, sensible levels, and define a normalization
  17. # instance which takes data values and translates those into levels.
  18. cmap = plt.get_cmap('PiYG')
  19. norm = BoundaryNorm(levels, ncolors=cmap.N, clip=True)
  20. fig, (ax0, ax1) = plt.subplots(nrows=2)
  21. im = ax0.pcolormesh(x, y, z, cmap=cmap, norm=norm)
  22. fig.colorbar(im, ax=ax0)
  23. ax0.set_title('pcolormesh with levels')
  24. # contours are *point* based plots, so convert our bound into point
  25. # centers
  26. cf = ax1.contourf(x[:-1, :-1] + dx/2.,
  27. y[:-1, :-1] + dy/2., z, levels=levels,
  28. cmap=cmap)
  29. fig.colorbar(cf, ax=ax1)
  30. ax1.set_title('contourf with levels')
  31. # adjust spacing between subplots so `ax1` title and `ax0` tick labels
  32. # don't overlap
  33. fig.tight_layout()
  34. plt.show()

pcolormesh示例

参考

下面的示例演示了以下函数和方法的使用:

  1. matplotlib.axes.Axes.pcolormesh
  2. matplotlib.pyplot.pcolormesh
  3. matplotlib.axes.Axes.contourf
  4. matplotlib.pyplot.contourf
  5. matplotlib.figure.Figure.colorbar
  6. matplotlib.pyplot.colorbar
  7. matplotlib.colors.BoundaryNorm
  8. matplotlib.ticker.MaxNLocator

下载这个示例