2

I'm trying to use a matplotlib SpanSelector inside a function. I modified the original example (http://matplotlib.org/examples/widgets/span_selector.html) but it didn't work. Here is the code:

#!/usr/bin/env python
"""
The SpanSelector is a mouse widget to select a xmin/xmax range and plot the
detail view of the selected region in the lower axes
"""
import numpy as npy
from pylab import figure, show
from matplotlib.widgets import SpanSelector

fig = figure(figsize=(8,6))
ax = fig.add_subplot(211, axisbg='#FFFFCC')

x = npy.arange(0.0, 5.0, 0.01)
y = npy.sin(2*npy.pi*x) + 0.5*npy.random.randn(len(x))

ax.plot(x, y, '-')
ax.set_ylim(-2,2)
ax.set_title('Press left mouse button and drag to test')

ax2 = fig.add_subplot(212, axisbg='#FFFFCC')
line2, = ax2.plot(x, y, '-')


def onselect(xmin, xmax):
    indmin, indmax = npy.searchsorted(x, (xmin, xmax))
    indmax = min(len(x)-1, indmax)

    thisx = x[indmin:indmax]
    thisy = y[indmin:indmax]
    line2.set_data(thisx, thisy)
    ax2.set_xlim(thisx[0], thisx[-1])
    ax2.set_ylim(thisy.min(), thisy.max())
    fig.canvas.draw()

## set useblit True on gtkagg for enhanced performance
# SpanSelector works this way
#span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
#                    rectprops=dict(alpha=0.5, facecolor='red') )

def fun_with_spanselector_inside():
    # set useblit True on gtkagg for enhanced performance
    span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
                        rectprops=dict(alpha=0.5, facecolor='red') )

# SpanSelector does not work this way
fun_with_spanselector_inside()

show()

I'm using Python 2.7, matplotlib 1.1.1rc on Ubuntu 12.04.

Why is this not working?

1 Answer 1

1

You just need to hold onto a reference to the SpanSelector instance. Otherwise, it's garbage collected.

Basically, you need to do this:

def fun_with_spanselector_inside():
    # set useblit True on gtkagg for enhanced performance
    span = SpanSelector(ax, onselect, 'horizontal', useblit=True,
                        rectprops=dict(alpha=0.5, facecolor='red') )
    return span

span = fun_with_spanselector_inside()

Note that this has nothing to do with it being inside a function. If you just do:

SpanSelector(ax, onselect, 'horizontal', useblit=True,
             rectprops=dict(alpha=0.5, facecolor='red'))

it won't work either.

This should be clearer in the documentation, though. I'm not sure offhand if this is by design or accident.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the answer. There is maybe something about it in http://matplotlib.org/users/event_handling.html.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.