I have a script which spawns a data plot with a SpanSelector widget. The widget calls a select_window(vmin, vmax)
closure function, which uses the window limits to analyse the chosen data. The analysis function spawns another plot with some visual results.
The default behaviour of SpanSelector is to execute select_window
immediately upon selection. Since the calculations are a bit heavy, I would like the user to confirm the selected window via keypress. The first option is to use plt.waitforbuttonpress
, but this responds to all key events including those used by default for pan/zoom/etc. in matplotlib.
The second option is to connect a key_press_event
directly, but I was unsure where to connect and disconnect the event handler.
Working example, using waitforbuttonpress:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector
def analyse(data, window_min, window_max):
sliced_data = data[window_min:window_max]
print(sliced_data)
fig, ax = plt.subplots()
ax.plot(sliced_data)
plt.pause(0.001)
def plot_data(data):
fig, ax = plt.subplots()
ax.plot(data)
def select_window(vmin, vmax):
if plt.waitforbuttonpress(60):
window_min = int(np.floor(vmin))
window_max = int(np.ceil(vmax))
analyse(data, window_min, window_max)
widget = SpanSelector(
ax, select_window, 'horizontal', useblit=True, span_stays=True,
minspan=1
)
plt.show()
return widget # Keeping a reference so it isn't garbage collected.
if __name__ == '__main__':
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
widget = plot_data(data)