{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n# Radio Buttons Grid\n\nUsing radio buttons in a 2D grid layout.\n\nRadio buttons can be arranged in a 2D grid by passing a ``(rows, cols)``\ntuple to the *layout* parameter. This is useful when you have multiple\nrelated options that are best displayed in a grid format rather than a\nvertical list.\n\nIn this example, we create a color picker using a 2D grid of radio buttons\nto select the line color of a plot.\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 RadioButtons\n\n# Generate sample data\nt = np.arange(0.0, 2.0, 0.01)\ns = np.sin(2 * np.pi * t)\n\nfig, (ax, ax_buttons) = plt.subplots(\n 1,\n 2,\n figsize=(8, 4),\n width_ratios=[4, 1.4],\n)\n\n# Create initial plot\n(line,) = ax.plot(t, s, lw=2, color=\"red\")\nax.set(xlabel=\"Time (s)\", ylabel=\"Amplitude\", title=\"Sine Wave - Click a color!\")\n\n# Configure the radio buttons axes\nax_buttons.set_facecolor(\"0.95\")\nax_buttons.spines[:].set_color(\"0.8\")\nax_buttons.set_title(\"Line Color\")\n# Create a 2D grid of color options (3 rows x 2 columns)\ncolors = [\"red\", \"yellow\", \"green\", \"purple\", \"brown\", \"gray\"]\nradio = RadioButtons(ax_buttons, colors, layout=(3, 2))\n\n\ndef update_color(label):\n \"\"\"Update the line color based on selected button.\"\"\"\n line.set_color(label)\n fig.canvas.draw()\nradio.on_clicked(update_color)\n\n\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.RadioButtons`\n\n.. tags::\n\n styling: color\n styling: conditional\n plot-type: line\n level: intermediate\n purpose: showcase\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.12.15" } }, "nbformat": 4, "nbformat_minor": 0 }