图像掩码

显示与掩码数组输入和范围以外的颜色。

第二个子图说明了如何使用边界规范来获得填充轮廓效果。

  1. from copy import copy
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. import matplotlib.colors as colors
  5. # compute some interesting data
  6. x0, x1 = -5, 5
  7. y0, y1 = -3, 3
  8. x = np.linspace(x0, x1, 500)
  9. y = np.linspace(y0, y1, 500)
  10. X, Y = np.meshgrid(x, y)
  11. Z1 = np.exp(-X**2 - Y**2)
  12. Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
  13. Z = (Z1 - Z2) * 2
  14. # Set up a colormap:
  15. # use copy so that we do not mutate the global colormap instance
  16. palette = copy(plt.cm.gray)
  17. palette.set_over('r', 1.0)
  18. palette.set_under('g', 1.0)
  19. palette.set_bad('b', 1.0)
  20. # Alternatively, we could use
  21. # palette.set_bad(alpha = 0.0)
  22. # to make the bad region transparent. This is the default.
  23. # If you comment out all the palette.set* lines, you will see
  24. # all the defaults; under and over will be colored with the
  25. # first and last colors in the palette, respectively.
  26. Zm = np.ma.masked_where(Z > 1.2, Z)
  27. # By setting vmin and vmax in the norm, we establish the
  28. # range to which the regular palette color scale is applied.
  29. # Anything above that range is colored based on palette.set_over, etc.
  30. # set up the Axes objets
  31. fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(6, 5.4))
  32. # plot using 'continuous' color map
  33. im = ax1.imshow(Zm, interpolation='bilinear',
  34. cmap=palette,
  35. norm=colors.Normalize(vmin=-1.0, vmax=1.0),
  36. aspect='auto',
  37. origin='lower',
  38. extent=[x0, x1, y0, y1])
  39. ax1.set_title('Green=low, Red=high, Blue=masked')
  40. cbar = fig.colorbar(im, extend='both', shrink=0.9, ax=ax1)
  41. cbar.set_label('uniform')
  42. for ticklabel in ax1.xaxis.get_ticklabels():
  43. ticklabel.set_visible(False)
  44. # Plot using a small number of colors, with unevenly spaced boundaries.
  45. im = ax2.imshow(Zm, interpolation='nearest',
  46. cmap=palette,
  47. norm=colors.BoundaryNorm([-1, -0.5, -0.2, 0, 0.2, 0.5, 1],
  48. ncolors=palette.N),
  49. aspect='auto',
  50. origin='lower',
  51. extent=[x0, x1, y0, y1])
  52. ax2.set_title('With BoundaryNorm')
  53. cbar = fig.colorbar(im, extend='both', spacing='proportional',
  54. shrink=0.9, ax=ax2)
  55. cbar.set_label('proportional')
  56. fig.suptitle('imshow, with out-of-range and masked data')
  57. plt.show()

图像掩码示例

参考

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

  1. import matplotlib
  2. matplotlib.axes.Axes.imshow
  3. matplotlib.pyplot.imshow
  4. matplotlib.figure.Figure.colorbar
  5. matplotlib.pyplot.colorbar
  6. matplotlib.colors.BoundaryNorm
  7. matplotlib.colorbar.ColorbarBase.set_label

下载这个示例