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:
JavaScript
x
24
24
1
import matplotlib.pyplot as plt
2
import numpy as np
3
4
keep_ploting = True
5
6
7
def action():
8
def key_event(event):
9
if event.key == 'escape':
10
global keep_ploting
11
keep_ploting = False
12
13
fig = plt.figure()
14
while keep_ploting:
15
plt.clf()
16
x = np.linspace(1, 10, 100)
17
y = np.random.weibull(2,100)
18
19
plt.plot(x, y)
20
plt.pause(1e-1)
21
fig.canvas.mpl_connect('key_press_event', key_event)
22
23
action()
24
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
JavaScript
1
11
11
1
while keep_ploting:
2
plt.clf()
3
x = np.linspace(1, 10, 100)
4
y = np.random.weibull(2,100)
5
6
plt.plot(x, y)
7
plt.pause(1e-1)
8
9
fig = plt.gcf() # get current figure
10
fig.canvas.mpl_connect('key_press_event', key_event)
11