Contourf 与记录颜色刻度

演示在 Contourf 中记录颜色的标度

  1. import matplotlib.pyplot as plt
  2. import numpy as np
  3. from numpy import ma
  4. from matplotlib import ticker, cm
  5. N = 100
  6. x = np.linspace(-3.0, 3.0, N)
  7. y = np.linspace(-2.0, 2.0, N)
  8. X, Y = np.meshgrid(x, y)
  9. # A low hump with a spike coming out.
  10. # Needs to have z/colour axis on a log scale so we see both hump and spike.
  11. # linear scale only shows the spike.
  12. Z1 = np.exp(-(X)**2 - (Y)**2)
  13. Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
  14. z = Z1 + 50 * Z2
  15. # Put in some negative values (lower left corner) to cause trouble with logs:
  16. z[:5, :5] = -1
  17. # The following is not strictly essential, but it will eliminate
  18. # a warning. Comment it out to see the warning.
  19. z = ma.masked_where(z <= 0, z)
  20. # Automatic selection of levels works; setting the
  21. # log locator tells contourf to use a log scale:
  22. fig, ax = plt.subplots()
  23. cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r)
  24. # Alternatively, you can manually set the levels
  25. # and the norm:
  26. # lev_exp = np.arange(np.floor(np.log10(z.min())-1),
  27. # np.ceil(np.log10(z.max())+1))
  28. # levs = np.power(10, lev_exp)
  29. # cs = ax.contourf(X, Y, z, levs, norm=colors.LogNorm())
  30. cbar = fig.colorbar(cs)
  31. plt.show()

Contourf 与记录颜色刻度示例

参考

本例中显示了以下函数、方法和类的使用:

  1. import matplotlib
  2. matplotlib.axes.Axes.contourf
  3. matplotlib.pyplot.contourf
  4. matplotlib.figure.Figure.colorbar
  5. matplotlib.pyplot.colorbar
  6. matplotlib.axes.Axes.legend
  7. matplotlib.pyplot.legend
  8. matplotlib.ticker.LogLocator

下载这个示例