修改坐标格式化程序

修改坐标格式化程序,以报告给定x和y的最近像素的图像“z”值。这个功能在默认情况下是内置的,但是展示如何自定义Format_coord函数仍然很有用。

  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. # Fixing random state for reproducibility
  4. np.random.seed(19680801)
  5. X = 10*np.random.rand(5, 3)
  6. fig, ax = plt.subplots()
  7. ax.imshow(X, interpolation='nearest')
  8. numrows, numcols = X.shape
  9. def format_coord(x, y):
  10. col = int(x + 0.5)
  11. row = int(y + 0.5)
  12. if col >= 0 and col < numcols and row >= 0 and row < numrows:
  13. z = X[row, col]
  14. return 'x=%1.4f, y=%1.4f, z=%1.4f' % (x, y, z)
  15. else:
  16. return 'x=%1.4f, y=%1.4f' % (x, y)
  17. ax.format_coord = format_coord
  18. plt.show()

修改坐标格式化程序

参考

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

  1. import matplotlib
  2. matplotlib.axes.Axes.format_coord
  3. matplotlib.axes.Axes.imshow

下载这个示例