Search code examples
pythonmatplotlibcursorcoordinatesinteractive

Change format/units of co-ords on matplotlib imshow


I would like the co-ords of the cursor to be a whole number instead of 5.75e+03. I have the same problem as this user (matplotlib coordinates format), I used the solution suggested to them which worked for them, but it did not work for me. This was the solution

ax.format_coord = lambda x, y: "({0:f}, ".format(y) +  "{0:f})".format(x)

Here is my plot:
enter image description here


Solution

  • You probably want to use the format :.0f instead of just :f. The latter doesn't fix the number of decimals. By default, matplotlib automatically chooses of format depending on the available space. If you resize the window, the default format can change. But this choice doesn't seem logical in every situation.

    In Python 3.6 f-strings were introduced, which simplifies the ways formatting can be written. For an extensive list of available format specifiers, see this document.

    Here is a minimal example:

    from matplotlib import pyplot as plt
    import numpy as np
    
    plt.imshow(np.random.rand(3, 5), extent=(0, 5000, 0, 3000))
    plt.gca().format_coord = lambda x, y: f"({x:.0f}, {y:.0f})"
    plt.show()
    

    example plot

    For older Python versions you can set format_coord to lambda x, y: "({0:.0f}, {1:.0f})".format(x, y)