1"""
2==================================
3Modifying the coordinate formatter
4==================================
5
6Modify the coordinate formatter to report the image "z"
7value of the nearest pixel given x and y
8"""
9import numpy as np
10import matplotlib.pyplot as plt
11
12# Fixing random state for reproducibility
13np.random.seed(19680801)
14
15
16X = 10*np.random.rand(5, 3)
17
18fig, ax = plt.subplots()
19ax.imshow(X, interpolation='nearest')
20
21numrows, numcols = X.shape
22
23
24def format_coord(x, y):
25    col = int(x + 0.5)
26    row = int(y + 0.5)
27    if col >= 0 and col < numcols and row >= 0 and row < numrows:
28        z = X[row, col]
29        return 'x=%1.4f, y=%1.4f, z=%1.4f' % (x, y, z)
30    else:
31        return 'x=%1.4f, y=%1.4f' % (x, y)
32
33ax.format_coord = format_coord
34plt.show()
35