3

I want to update subplots based on a SpanSelector which works as expected. But another requirement is that I need to initialize the selected span to some given values. I have tried to call the _press, _release functions but they just return False and nothing happens. How can I set the span programmatically such that the selected span is visible in the SpanSelector as well?

from matplotlib.widgets import SpanSelector
from collections import namedtuple

widgets.append(
    SpanSelector(range_ax, onselect=self._plot_subplots, direction='horizontal', rectprops=dict(alpha=0.5, facecolor='red'), span_stays=True)
)

# fake some events
Event = namedtuple('Event', ['xdata', 'ydata'])
widgets[0]._press(Event(0, 119))
widgets[0]._release(Event(500, 120))
KIC
  • 5,887
  • 7
  • 58
  • 98

2 Answers2

1

Set the selection rectangle stay_rect and call the onselect handler with the initial xmin and xmax values.

Example: initial view of the example from the docs with the following inserted before plt.show():

xmin, xmax = 3, 4 
span.stay_rect.set_bounds(xmin, 0, xmax-xmin, 1)
span.stay_rect.set_visible(True)
span.onselect(xmin, xmax)

enter image description here

Stef
  • 28,728
  • 2
  • 24
  • 52
  • This shows the desired chart true, but it doesn't show the selected range `span_stays=True` – KIC Jan 04 '21 at 11:17
1

I think that using extents is cleaner. Based on the example from the docs, you can do the following:

span = SpanSelector(
    ax1,
    onselect,
    "horizontal",
    useblit=True,
    props=dict(alpha=0.5, facecolor="tab:blue"),
    interactive=True,
    drag_from_anywhere=True,
    span_stays=True,  # Add this to make SpanSelector persistent
)

# Set default values
xmin, xmax = 1, 4
span.extents = (xmin, xmax)
span.onselect(xmin, xmax)