X Tutup
Skip to content
Merged
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()
73 changes: 73 additions & 0 deletions galleries/examples/widgets/radio_buttons_grid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""
==================
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`
#
# .. tags::
#
# styling: color
# styling: conditional
# plot-type: line
# level: intermediate
# purpose: showcase
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
26 changes: 24 additions & 2 deletions lib/matplotlib/tests/test_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -1164,6 +1164,29 @@ def test_radio_buttons_props(fig_test, fig_ref):
cb.set_radio_props({**radio_props, 's': (24 / 2)**2})


@image_comparison(['check_radio_grid_buttons.png'], style='mpl20', remove_text=True)
def test_radio_grid_buttons():
fig = plt.figure()
rb_horizontal = widgets.RadioButtons(
fig.add_axes((0.1, 0.05, 0.65, 0.05)),
["tea", "coffee", "chocolate milk", "water", "soda", "coke"],
layout='horizontal',
active=4,
)
cb_grid = widgets.CheckButtons(
fig.add_axes((0.1, 0.15, 0.25, 0.05*3)),
["Chicken", "Salad", "Rice", "Sushi", "Pizza", "Fries"],
layout=(3, 2),
actives=[True, True, False, False, False, True],
)
rb_vertical = widgets.RadioButtons(
fig.add_axes((0.1, 0.35, 0.2, 0.05*4)),
["Trinity Cream", "Cake", "Ice Cream", "Muhallebi"],
layout='vertical',
active=3,
)


def test_radio_button_active_conflict(ax):
with pytest.warns(UserWarning,
match=r'Both the \*activecolor\* parameter'):
Expand Down Expand Up @@ -1229,8 +1252,7 @@ def test__buttons_callbacks(ax, widget):
"button_press_event",
ax,
ax.transData.inverted().transform(ax.transAxes.transform(
# (x, y) of the 0th button defined at
# `{Check,Radio}Buttons._init_props`
# (x, y) of the 0th button defined at `_Buttons._init_layout`
(0.15, 0.5),
)),
1,
Expand Down
Loading
Loading
X Tutup