Skip to content
Advertisement

Matplotlib figure key_event connection after closing window in recreating loop

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()

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement