

.. _sphx_glr_gallery_api_image_zcoord.py:


==================================
Modifying the coordinate formatter
==================================

Modify the coordinate formatter to report the image "z"
value of the nearest pixel given x and y




.. image:: /gallery/api/images/sphx_glr_image_zcoord_001.png
    :align: center





.. code-block:: python

    import numpy as np
    import matplotlib.pyplot as plt

    # Fixing random state for reproducibility
    np.random.seed(19680801)


    X = 10*np.random.rand(5, 3)

    fig, ax = plt.subplots()
    ax.imshow(X, interpolation='nearest')

    numrows, numcols = X.shape


    def format_coord(x, y):
        col = int(x + 0.5)
        row = int(y + 0.5)
        if col >= 0 and col < numcols and row >= 0 and row < numrows:
            z = X[row, col]
            return 'x=%1.4f, y=%1.4f, z=%1.4f' % (x, y, z)
        else:
            return 'x=%1.4f, y=%1.4f' % (x, y)

    ax.format_coord = format_coord
    plt.show()

**Total running time of the script:** ( 0 minutes  0.046 seconds)



.. only :: html

 .. container:: sphx-glr-footer


  .. container:: sphx-glr-download

     :download:`Download Python source code: image_zcoord.py <image_zcoord.py>`



  .. container:: sphx-glr-download

     :download:`Download Jupyter notebook: image_zcoord.ipynb <image_zcoord.ipynb>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.readthedocs.io>`_
