颜色条

通过指定可映射对象(此处为imshow返回的 AxesImage )和要将颜色条附加到的轴来使用 colorbar

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # setup some generic data
  4. N = 37
  5. x, y = np.mgrid[:N, :N]
  6. Z = (np.cos(x*0.2) + np.sin(y*0.3))
  7. # mask out the negative and positive values, respectively
  8. Zpos = np.ma.masked_less(Z, 0)
  9. Zneg = np.ma.masked_greater(Z, 0)
  10. fig, (ax1, ax2, ax3) = plt.subplots(figsize=(13, 3), ncols=3)
  11. # plot just the positive data and save the
  12. # color "mappable" object returned by ax1.imshow
  13. pos = ax1.imshow(Zpos, cmap='Blues', interpolation='none')
  14. # add the colorbar using the figure's method,
  15. # telling which mappable we're talking about and
  16. # which axes object it should be near
  17. fig.colorbar(pos, ax=ax1)
  18. # repeat everything above for the negative data
  19. neg = ax2.imshow(Zneg, cmap='Reds_r', interpolation='none')
  20. fig.colorbar(neg, ax=ax2)
  21. # Plot both positive and negative values betwen +/- 1.2
  22. pos_neg_clipped = ax3.imshow(Z, cmap='RdBu', vmin=-1.2, vmax=1.2,
  23. interpolation='none')
  24. # Add minorticks on the colorbar to make it easy to read the
  25. # values off the colorbar.
  26. cbar = fig.colorbar(pos_neg_clipped, ax=ax3, extend='both')
  27. cbar.minorticks_on()
  28. plt.show()

颜色条示例

参考

此示例中显示了以下函数,方法,类和模块的使用:

  1. import matplotlib
  2. import matplotlib.colorbar
  3. matplotlib.axes.Axes.imshow
  4. matplotlib.pyplot.imshow
  5. matplotlib.figure.Figure.colorbar
  6. matplotlib.pyplot.colorbar
  7. matplotlib.colorbar.Colorbar.minorticks_on
  8. matplotlib.colorbar.Colorbar.minorticks_off

下载这个示例