Search code examples
pythonmatplotlibjupyter-notebookmplcursors

How to increase the number of digits of x and y coordinates shown?


Using the %matplotlib notebook in matplotlib we get the plot

plot

How to increase the number of digits after the decimal point in the x and y coordinates, displayed after passing my mouse over the graph?

And thank you.


Solution

  • Here is a minimal example using mplcursors. The hover option is set, so the functionality is called while hovering (instead of only when clicking).

    Standard a yellow annotation window is shown, of which you can update the text. You can disable this annotation if you only want to display something in the status bar.

    The code below shows the cursor coordinates when hovering close to the curve. The default cursor display is disabled.

    This other post shows an example how mplcursors can identify a local maximum.

    from matplotlib import pyplot as plt
    import mplcursors
    import numpy as np
    
    def show_annotation(sel):
        sel.annotation.set_visible(False)
        fig.canvas.toolbar.set_message(f'{sel.annotation.xy[0]:.12f};{sel.annotation.xy[1]:.12f}')
    
    fig, ax = plt.subplots()
    
    x = np.linspace(0, 10)
    ax.plot(x, np.sin(x))
    
    fig.canvas.mpl_connect("motion_notify_event",
                           lambda event: fig.canvas.toolbar.set_message(""))
    cursor = mplcursors.cursor(hover=True)
    cursor.connect("add", show_annotation)
    

    PS: To just use the standard annotation, you can write show_annotation as follows:

    def show_annotation(sel):
        sel.annotation.set_text(f'x:{sel.annotation.xy[0]:.12f}\ny:{sel.annotation.xy[1]:.12f}')
    

    Mplcursors seems not to be showing annotations or status bar updates after zooming in while in hovering mode. Setting hover=False (the default mode) would result in the same behavior, but only after a click (or double click when zoomed).

    from matplotlib import pyplot as plt
    import mplcursors
    import numpy as np
    
    def show_annotation(sel):
        sel.annotation.set_visible(False)
        fig.canvas.toolbar.set_message(f'{sel.annotation.xy[0]:.12f};{sel.annotation.xy[1]:.12f}')
    
    fig, ax = plt.subplots()
    
    x = np.linspace(0, 10)
    ax.plot(x, np.sin(x))
    
    cursor = mplcursors.cursor(hover=False)
    cursor.connect("add", show_annotation)
    plt.show()
    

    To always see the decimals, independent of being near a curve, you could try the following (without mplcursors):

    fig.canvas.mpl_connect("motion_notify_event",
                            lambda event: fig.canvas.toolbar.set_message(f"{event.xdata:.12f};{event.ydata:.12f}"))