How to set the min and max value for SpanSelector widget programmatically

Viewed 241

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))
2 Answers

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

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