[Python] Capturing Matplotlib coordinates with mouse clicks using ipywidgets in Jupyter...

Discussão em 'Python' iniciado por Stack, Outubro 24, 2024.

  1. Stack

    Stack Membro Participativo

    Short question


    I want to capture coordinates by clicking different locations with a mouse on a Matplotlib figure inside a Jupyter Notebook. I want to use ipywidgets without using any Matplotlib magic command (like %matplotlib ipympl) to switch the backend and without using extra packages apart from Matplotlib, ipywidgets and Numpy.

    Detailed explanation


    I know how to achieve this using the ipympl package and the corresponding Jupyter magic command %matplotlib ipympl to switch the backend from inline to ipympl (see HERE).

    After installing ipympl, e.g. with conda install ipympl, and switching to the ipympl backend, one can follow this procedure to capture mouse click coordinates in Matplotlib.

    import matplotlib.pyplot as plt

    # Function to store mouse-click coordinates
    def onclick(event):
    x, y = event.xdata, event.ydata
    plt.plot(x, y, 'ro')
    xy.append((x, y))

    # %%
    # Start Matplotlib interactive mode
    %matplotlib ipympl

    plt.plot([0, 1])
    xy = [] # Initializes coordinates
    plt.connect('button_press_event', onclick)


    [​IMG]

    However, I find this switching back and forth between inline and ipympl backend quite confusing in a Notebook.

    An alternative for interactive Matplotlib plotting in Jupyter Notebook is to use the ipywidgets package. For example, with the interact command one can easily create sliders for Matplotlib plots, without the need to switcxh backend. (see HERE).

    from ipywidgets import interact
    import numpy as np
    import matplotlib.pyplot as plt

    x = np.linspace(0, 2 * np.pi)

    def update(w=1.0):
    plt.plot(np.sin(w * x))
    plt.show()

    interact(update);


    [​IMG]

    However, I have not found a way to use the ipywidgets package to capture (x,y) coordinates from mouse clicks, equivalent to my above example using ipympl.

    Continue reading...

Compartilhe esta Página