0

I have the following minimalistic code that works perfectly fine: a continuous while loop keeps plotting my data and if I press the escape key the plotting stops. Now, if one closes the matplotlib-window a new appears because of the plt.pause command, but now the key_event is not attached anymore. Is there a way to keep the connection of new appearing windows and the key_event?

Code:

import matplotlib.pyplot as plt
import numpy as np

keep_ploting = True


def action():
    def key_event(event):
        if event.key == 'escape':
            global keep_ploting
            keep_ploting = False

    fig = plt.figure()
    while keep_ploting:
        plt.clf()
        x = np.linspace(1, 10, 100)
        y = np.random.weibull(2,100)

        plt.plot(x, y)
        plt.pause(1e-1)
        fig.canvas.mpl_connect('key_press_event', key_event)

action()

1 Answer 1

1

When you close window then it creates new figure and you should use gcf() (get current figure) to assign event to new figure

while keep_ploting:
    plt.clf()
    x = np.linspace(1, 10, 100)
    y = np.random.weibull(2,100)

    plt.plot(x, y)
    plt.pause(1e-1)
    
    fig = plt.gcf()  # get current figure
    fig.canvas.mpl_connect('key_press_event', key_event)
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, I knew there would be that kind of command I just don't know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.