Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions doc/release/next_whats_new/radio_buttons_2d_grid.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
RadioButtons and CheckButtons widgets support flexible layouts
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The `.widgets.RadioButtons` and `.widgets.CheckButtons` widgets now support
arranging buttons in different layouts via the new *layout* parameter. You can
arrange buttons vertically (default), horizontally, or in a 2D grid by passing
a ``(rows, cols)`` tuple.

See :doc:`/gallery/widgets/radio_buttons_grid` for a ``(rows, cols)`` example.

.. plot::
:include-source: true
:alt: Multiple sine waves with checkboxes to toggle their visibility.

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import CheckButtons

t = np.arange(0.0, 2.0, 0.01)
s0 = np.sin(2*np.pi*t)
s1 = np.sin(4*np.pi*t)
s2 = np.sin(6*np.pi*t)
s3 = np.sin(8*np.pi*t)

fig, axes = plt.subplot_mosaic(
[['main'], ['buttons']],
height_ratios=[8, 1],
layout="constrained",
)

l0, = axes['main'].plot(t, s0, lw=2, color='red', label='2 Hz')
l1, = axes['main'].plot(t, s1, lw=2, color='green', label='4 Hz')
l2, = axes['main'].plot(t, s2, lw=2, color='blue', label='6 Hz')
l3, = axes['main'].plot(t, s3, lw=2, color='purple', label='8 Hz')
axes['main'].set_xlabel('Time (s)')
axes['main'].set_ylabel('Amplitude')

lines_by_label = {l.get_label(): l for l in [l0, l1, l2, l3]}

axes['buttons'].set_facecolor('0.9')
check = CheckButtons(
axes['buttons'],
labels=lines_by_label.keys(),
actives=[l.get_visible() for l in lines_by_label.values()],
layout='horizontal'
)

def callback(label):
ln = lines_by_label[label]
ln.set_visible(not ln.get_visible())
fig.canvas.draw_idle()

check.on_clicked(callback)
plt.show()
65 changes: 65 additions & 0 deletions galleries/examples/widgets/radio_buttons_grid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""
==================
Radio Buttons Grid
==================

Using radio buttons in a 2D grid layout.

Radio buttons can be arranged in a 2D grid by passing a ``(rows, cols)``
tuple to the *layout* parameter. This is useful when you have multiple
related options that are best displayed in a grid format rather than a
vertical list.

In this example, we create a color picker using a 2D grid of radio buttons
to select the line color of a plot.
"""

import matplotlib.pyplot as plt
import numpy as np

from matplotlib.widgets import RadioButtons

# Generate sample data
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2 * np.pi * t)

fig, (ax_plot, ax_buttons) = plt.subplots(
1,
2,
figsize=(8, 4),
width_ratios=[4, 1.4],
)

# Create initial plot
(line,) = ax_plot.plot(t, s, lw=2, color="red")
ax_plot.set_xlabel("Time (s)")
ax_plot.set_ylabel("Amplitude")
ax_plot.set_title("Sine Wave - Click a color!")
ax_plot.grid(True, alpha=0.3)

# Configure the radio buttons axes
ax_buttons.set_facecolor("0.9")
ax_buttons.set_title("Line Color", fontsize=12, pad=10)
# Create a 2D grid of color options (3 rows x 2 columns)
colors = ["red", "yellow", "green", "purple", "brown", "gray"]
radio = RadioButtons(ax_buttons, colors, layout=(3, 2))


def color_func(label):
"""Update the line color based on selected button."""
line.set_color(label)
fig.canvas.draw()


radio.on_clicked(color_func)

plt.show()

# %%
#
# .. admonition:: References
#
# The use of the following functions, methods, classes and modules is shown
# in this example:
#
# - `matplotlib.widgets.RadioButtons`
Loading
Loading