[Python] Why does matplotlib draw updates for the first interactive plot I show, but not the...

Discussão em 'Python' iniciado por Stack, Fevereiro 10, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to show two interactive plots. The second plot is displayed after the first plot is closed. In this minimal example, the interactive part just draws a dot wherever the user clicks and prints the coordinates to the console.

    import matplotlib.pyplot as plt

    def onclick(event):
    # This prints both times
    print(event.xdata, event.ydata)
    # This only works the first time
    plt.scatter(event.xdata, event.ydata)

    for i in range(2):
    plt.plot([1, 2, 3, 4])
    plt.gca().figure.canvas.mpl_connect('button_press_event', onclick)
    with plt.ion():
    plt.show(block=True)


    Using the code above, dots don't show up on the second plot. It still prints the coordinates, so the event is firing; it's just not drawing. Everything else works.

    Things I've tried that didn't help:

    • Different backends (Qt, Tk)
    • plt.close() as the last step inside loop
    • plt.pause(1) as the last step inside loop
    • Using plt.ion() and plt.ioff() instead of the context manager
    • Manually detaching the event at the end of the loop, using canvas.mpl_disconnect(cid) with the cid returned from mpl_connect
    • plt.draw() & plt.pause(1) to try and force updates
    • Copying and pasting the same code twice instead of using a loop
    • Using fig, ax = plt.subplots() in the loop and ax.scatter() in the onclick handler to explicitly plot to the same axes

    I'm using matplotlib 3.9.4 in Python 3.9.20 for compatibility with things beyond my control.

    Continue reading...

Compartilhe esta Página