等高线标签演示

说明一些可以用等高线的标签做的更高级的东西。

另请参见轮廓演示示例

  1. import matplotlib
  2. import numpy as np
  3. import matplotlib.ticker as ticker
  4. import matplotlib.pyplot as plt

定义我们的外观

  1. delta = 0.025
  2. x = np.arange(-3.0, 3.0, delta)
  3. y = np.arange(-2.0, 2.0, delta)
  4. X, Y = np.meshgrid(x, y)
  5. Z1 = np.exp(-X**2 - Y**2)
  6. Z2 = np.exp(-(X - 1)**2 - (Y - 1)**2)
  7. Z = (Z1 - Z2) * 2

使用创造性的浮动类制作等高线的标签,遵循曼纽尔·梅茨的建议。

  1. # Define a class that forces representation of float to look a certain way
  2. # This remove trailing zero so '1.0' becomes '1'
  3. class nf(float):
  4. def __repr__(self):
  5. str = '%.1f' % (self.__float__(),)
  6. if str[-1] == '0':
  7. return '%.0f' % self.__float__()
  8. else:
  9. return '%.1f' % self.__float__()
  10. # Basic contour plot
  11. fig, ax = plt.subplots()
  12. CS = ax.contour(X, Y, Z)
  13. # Recast levels to new class
  14. CS.levels = [nf(val) for val in CS.levels]
  15. # Label levels with specially formatted floats
  16. if plt.rcParams["text.usetex"]:
  17. fmt = r'%r \%%'
  18. else:
  19. fmt = '%r %%'
  20. ax.clabel(CS, CS.levels, inline=True, fmt=fmt, fontsize=10)

等高线标签演示示例

使用字典用任意字符串标记等高线

  1. fig1, ax1 = plt.subplots()
  2. # Basic contour plot
  3. CS1 = ax1.contour(X, Y, Z)
  4. fmt = {}
  5. strs = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh']
  6. for l, s in zip(CS1.levels, strs):
  7. fmt[l] = s
  8. # Label every other level using strings
  9. ax1.clabel(CS1, CS1.levels[::2], inline=True, fmt=fmt, fontsize=10)

等高线标签演示示例2

使用Formatter来格式化

  1. fig2, ax2 = plt.subplots()
  2. CS2 = ax2.contour(X, Y, 100**Z, locator=plt.LogLocator())
  3. fmt = ticker.LogFormatterMathtext()
  4. fmt.create_dummy_axis()
  5. ax2.clabel(CS2, CS2.levels, fmt=fmt)
  6. ax2.set_title("$100^Z$")
  7. plt.show()

等高线标签演示示例3

参考

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

  1. matplotlib.axes.Axes.contour
  2. matplotlib.pyplot.contour
  3. matplotlib.axes.Axes.clabel
  4. matplotlib.pyplot.clabel
  5. matplotlib.ticker.LogFormatterMathtext
  6. matplotlib.ticker.TickHelper.create_dummy_axis

下载这个示例