.. only:: html
.. note::
:class: sphx-glr-download-link-note
Click :ref:`here ` to download the full example code
.. rst-class:: sphx-glr-example-title
.. _sphx_glr_gallery_widgets_span_selector.py:
=============
Span Selector
=============
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
.. code-block:: default
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import SpanSelector
# Fixing random state for reproducibility
np.random.seed(19680801)
fig, (ax1, ax2) = plt.subplots(2, figsize=(8, 6))
ax1.set(facecolor='#FFFFCC')
x = np.arange(0.0, 5.0, 0.01)
y = np.sin(2*np.pi*x) + 0.5*np.random.randn(len(x))
ax1.plot(x, y, '-')
ax1.set_ylim(-2, 2)
ax1.set_title('Press left mouse button and drag to test')
ax2.set(facecolor='#FFFFCC')
line2, = ax2.plot(x, y, '-')
def onselect(xmin, xmax):
indmin, indmax = np.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()
.. image:: /gallery/widgets/images/sphx_glr_span_selector_001.png
:alt: Press left mouse button and drag to test
:class: sphx-glr-single-img
.. note::
If the SpanSelector object is garbage collected you will lose the
interactivity. You must keep a hard reference to it to prevent this.
.. code-block:: default
span = SpanSelector(ax1, onselect, 'horizontal', useblit=True,
rectprops=dict(alpha=0.5, facecolor='red'))
# Set useblit=True on most backends for enhanced performance.
plt.show()
.. rst-class:: sphx-glr-timing
**Total running time of the script:** ( 0 minutes 1.000 seconds)
.. _sphx_glr_download_gallery_widgets_span_selector.py:
.. only :: html
.. container:: sphx-glr-footer
:class: sphx-glr-footer-example
.. container:: sphx-glr-download sphx-glr-download-python
:download:`Download Python source code: span_selector.py `
.. container:: sphx-glr-download sphx-glr-download-jupyter
:download:`Download Jupyter notebook: span_selector.ipynb `
.. only:: html
.. rst-class:: sphx-glr-signature
Keywords: matplotlib code example, codex, python plot, pyplot
`Gallery generated by Sphinx-Gallery
`_