[Python] Storing mouse click event coordinates of graph with matplotlib

Discussão em 'Python' iniciado por Stack, Julho 9, 2025.

  1. Stack

    Stack Membro Participativo

    I am attempting to store coordinates from two mouse clicks in an interactive matplotlib graph in JupyterLab. I have managed to interact with the plot and get the x and y coordinates to print upon clicking. However, when I try to store those coordinates by appending to a list or numpy array (tried both), the values are not saving in my global variable coords. Since I can get the coordinates for one click successfully as ix and iy, I suppose I could have duplicate cells each with one click event each, but I'd prefer to have a single cell that can store both clicks' coordinates.

    My original code was taken from this question. I have had to make a few adjustments to work with ipympl and ipywidgets.

    Specifically, coords prints as empty even though my if statement regarding its length does seem to terminate the click event. Maybe I am missing something obvious (I am relatively new to Python from a MATLAB background). I'd appreciate any advice or alternative approaches to the issue.

    %matplotlib ipympl

    import pandas as pd
    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.optimize import curve_fit
    from scipy import stats
    import os
    import ipywidgets as widgets

    out = widgets.Output()
    coords = []

    fig, ax = plt.subplots(figsize =(4, 4))
    ax.plot(time,temp,'k-',linewidth = 1.5)
    ax.set_xlabel("Time (sec)")
    ax.set_ylabel(r"Temperature ($\degree$ C)")
    ax.tick_params(axis="both",direction='in',top=True, right=True)

    plt.show()

    @out.capture()
    def onclick(event):
    ix, iy = event.xdata, event.ydata
    print ('x = ',ix, 'y = ',iy)

    global coords
    coords.append(ix)
    coords.append(iy)

    # Disconnect after 2 clicks
    if len(coords) == 4:
    fig.canvas.mpl_disconnect(cid)

    return coords

    cid = fig.canvas.mpl_connect('button_press_event', onclick)
    display(out)
    print(coords)


    image of interactive figure and printed coordinates, for reference

    Continue reading...

Compartilhe esta Página