{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Image scaling using a RangeSlider\n\nUsing the RangeSlider widget to control the thresholding of an image.\n\nThe RangeSlider widget can be used similarly to the `.widgets.Slider`\nwidget. The major difference is that RangeSlider's ``val`` attribute\nis a tuple of floats ``(lower val, upper val)`` rather than a single float.\n\nSee :doc:`/gallery/widgets/slider_demo` for an example of using\na ``Slider`` to control a single float.\n\nSee :doc:`/gallery/widgets/slider_snap_demo` for an example of having\nthe ``Slider`` snap to discrete values.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import matplotlib.pyplot as plt\nimport numpy as np\n\nfrom matplotlib.widgets import RangeSlider\n\n# generate a fake image\nnp.random.seed(19680801)\nN = 128\nimg = np.random.randn(N, N)\n\nfig, axs = plt.subplots(1, 2, figsize=(10, 5))\nfig.subplots_adjust(bottom=0.25)\n\nim = axs[0].imshow(img)\naxs[1].hist(img.flatten(), bins='auto')\naxs[1].set_title('Histogram of pixel intensities')\n\n# Create the RangeSlider\nslider_ax = fig.add_axes([0.20, 0.1, 0.60, 0.03])\nslider = RangeSlider(slider_ax, \"Threshold\", img.min(), img.max())\n\n# Create the Vertical lines on the histogram\nlower_limit_line = axs[1].axvline(slider.val[0], color='k')\nupper_limit_line = axs[1].axvline(slider.val[1], color='k')\n\n\ndef update(val):\n # The val passed to a callback by the RangeSlider will\n # be a tuple of (min, max)\n\n # Update the image's colormap\n im.norm.vmin = val[0]\n im.norm.vmax = val[1]\n\n # Update the position of the vertical lines\n lower_limit_line.set_xdata([val[0], val[0]])\n upper_limit_line.set_xdata([val[1], val[1]])\n\n # Redraw the figure to ensure it updates\n fig.canvas.draw_idle()\n\n\nslider.on_changed(update)\nplt.show()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ ".. admonition:: References\n\n The use of the following functions, methods, classes and modules is shown\n in this example:\n\n - `matplotlib.widgets.RangeSlider`\n\n" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.13.2" } }, "nbformat": 4, "nbformat_minor": 0 }