Skip to content

Add styling support to Check and Radio buttons #24838

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 23, 2023
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
31 changes: 31 additions & 0 deletions doc/users/next_whats_new/widget_button_styling.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
Custom styling of button widgets
--------------------------------

Additional custom styling of button widgets may be achieved via the
*label_props* and *radio_props* arguments to `.RadioButtons`; and the
*label_props*, *frame_props*, and *check_props* arguments to `.CheckButtons`.

.. plot::

from matplotlib.widgets import CheckButtons, RadioButtons

fig, ax = plt.subplots(nrows=2, ncols=2, figsize=(5, 2), width_ratios=[1, 2])
default_rb = RadioButtons(ax[0, 0], ['Apples', 'Oranges'])
styled_rb = RadioButtons(ax[0, 1], ['Apples', 'Oranges'],
label_props={'color': ['red', 'orange'],
'fontsize': [16, 20]},
radio_props={'edgecolor': ['red', 'orange'],
'facecolor': ['mistyrose', 'peachpuff']})

default_cb = CheckButtons(ax[1, 0], ['Apples', 'Oranges'],
actives=[True, True])
styled_cb = CheckButtons(ax[1, 1], ['Apples', 'Oranges'],
actives=[True, True],
label_props={'color': ['red', 'orange'],
'fontsize': [16, 20]},
frame_props={'edgecolor': ['red', 'orange'],
'facecolor': ['mistyrose', 'peachpuff']},
check_props={'color': ['darkred', 'darkorange']})

ax[0, 0].set_title('Default')
ax[0, 1].set_title('Stylized')
12 changes: 8 additions & 4 deletions examples/widgets/check_buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,19 +20,23 @@
s2 = np.sin(6*np.pi*t)

fig, ax = plt.subplots()
l0, = ax.plot(t, s0, visible=False, lw=2, color='k', label='2 Hz')
l1, = ax.plot(t, s1, lw=2, color='r', label='4 Hz')
l2, = ax.plot(t, s2, lw=2, color='g', label='6 Hz')
l0, = ax.plot(t, s0, visible=False, lw=2, color='black', label='1 Hz')
l1, = ax.plot(t, s1, lw=2, color='red', label='2 Hz')
l2, = ax.plot(t, s2, lw=2, color='green', label='3 Hz')
fig.subplots_adjust(left=0.2)

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

# Make checkbuttons with all plotted lines with correct visibility
rax = fig.add_axes([0.05, 0.4, 0.1, 0.15])
check = CheckButtons(
ax=rax,
labels=lines_by_label.keys(),
actives=[l.get_visible() for l in lines_by_label.values()]
actives=[l.get_visible() for l in lines_by_label.values()],
label_props={'color': line_colors},
frame_props={'edgecolor': line_colors},
check_props={'facecolor': line_colors},
)


Expand Down
20 changes: 14 additions & 6 deletions examples/widgets/radio_buttons.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,23 +25,31 @@

axcolor = 'lightgoldenrodyellow'
rax = fig.add_axes([0.05, 0.7, 0.15, 0.15], facecolor=axcolor)
radio = RadioButtons(rax, ('2 Hz', '4 Hz', '8 Hz'))
radio = RadioButtons(rax, ('1 Hz', '2 Hz', '4 Hz'),
label_props={'color': 'cmy', 'fontsize': [12, 14, 16]},
radio_props={'s': [16, 32, 64]})


def hzfunc(label):
hzdict = {'2 Hz': s0, '4 Hz': s1, '8 Hz': s2}
hzdict = {'1 Hz': s0, '2 Hz': s1, '4 Hz': s2}
ydata = hzdict[label]
l.set_ydata(ydata)
plt.draw()
fig.canvas.draw()
radio.on_clicked(hzfunc)

rax = fig.add_axes([0.05, 0.4, 0.15, 0.15], facecolor=axcolor)
radio2 = RadioButtons(rax, ('red', 'blue', 'green'))
radio2 = RadioButtons(
rax, ('red', 'blue', 'green'),
label_props={'color': ['red', 'blue', 'green']},
radio_props={
'facecolor': ['red', 'blue', 'green'],
'edgecolor': ['darkred', 'darkblue', 'darkgreen'],
})


def colorfunc(label):
l.set_color(label)
plt.draw()
fig.canvas.draw()
radio2.on_clicked(colorfunc)

rax = fig.add_axes([0.05, 0.1, 0.15, 0.15], facecolor=axcolor)
Expand All @@ -50,7 +58,7 @@ def colorfunc(label):

def stylefunc(label):
l.set_linestyle(label)
plt.draw()
fig.canvas.draw()
radio3.on_clicked(stylefunc)

plt.show()
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
95 changes: 85 additions & 10 deletions lib/matplotlib/tests/test_widgets.py
Original file line number Diff line number Diff line change
Expand Up @@ -992,21 +992,38 @@ def test_TextBox(ax, toolbar):
@image_comparison(['check_radio_buttons.png'], style='mpl20', remove_text=True)
def test_check_radio_buttons_image():
ax = get_ax()
# Remove this line when this test image is regenerated.
plt.rcParams['text.kerning_factor'] = 6
fig = ax.figure
fig.subplots_adjust(left=0.3)

plt.subplots_adjust(left=0.3)
rax1 = plt.axes([0.05, 0.7, 0.15, 0.15])
rax2 = plt.axes([0.05, 0.2, 0.15, 0.15])
rb = widgets.RadioButtons(rax1, ('Radio 1', 'Radio 2', 'Radio 3'))
rax1 = fig.add_axes([0.05, 0.7, 0.2, 0.15])
rb1 = widgets.RadioButtons(rax1, ('Radio 1', 'Radio 2', 'Radio 3'))
with pytest.warns(DeprecationWarning,
match='The circles attribute was deprecated'):
rb.circles # Trigger the old-style elliptic radiobuttons.
cb = widgets.CheckButtons(rax2, ('Check 1', 'Check 2', 'Check 3'),
(False, True, True))
rb1.circles # Trigger the old-style elliptic radiobuttons.

rax2 = fig.add_axes([0.05, 0.5, 0.2, 0.15])
cb1 = widgets.CheckButtons(rax2, ('Check 1', 'Check 2', 'Check 3'),
(False, True, True))
with pytest.warns(DeprecationWarning,
match='The rectangles attribute was deprecated'):
cb.rectangles # Trigger old-style Rectangle check boxes
cb1.rectangles # Trigger old-style Rectangle check boxes

rax3 = fig.add_axes([0.05, 0.3, 0.2, 0.15])
rb3 = widgets.RadioButtons(
rax3, ('Radio 1', 'Radio 2', 'Radio 3'),
label_props={'fontsize': [8, 12, 16],
'color': ['red', 'green', 'blue']},
radio_props={'edgecolor': ['red', 'green', 'blue'],
'facecolor': ['mistyrose', 'palegreen', 'lightblue']})

rax4 = fig.add_axes([0.05, 0.1, 0.2, 0.15])
cb4 = widgets.CheckButtons(
rax4, ('Check 1', 'Check 2', 'Check 3'), (False, True, True),
label_props={'fontsize': [8, 12, 16],
'color': ['red', 'green', 'blue']},
frame_props={'edgecolor': ['red', 'green', 'blue'],
'facecolor': ['mistyrose', 'palegreen', 'lightblue']},
check_props={'color': ['red', 'green', 'blue']})


@check_figures_equal(extensions=["png"])
Expand All @@ -1019,6 +1036,41 @@ def test_radio_buttons(fig_test, fig_ref):
ax.text(.25, 1/3, "coffee", transform=ax.transAxes, va="center")


@check_figures_equal(extensions=['png'])
def test_radio_buttons_props(fig_test, fig_ref):
label_props = {'color': ['red'], 'fontsize': [24]}
radio_props = {'facecolor': 'green', 'edgecolor': 'blue', 'linewidth': 2}

widgets.RadioButtons(fig_ref.subplots(), ['tea', 'coffee'],
label_props=label_props, radio_props=radio_props)

cb = widgets.RadioButtons(fig_test.subplots(), ['tea', 'coffee'])
cb.set_label_props(label_props)
# Setting the label size automatically increases default marker size, so we
# need to do that here as well.
cb.set_radio_props({**radio_props, 's': (24 / 2)**2})


def test_radio_button_active_conflict(ax):
with pytest.warns(UserWarning,
match=r'Both the \*activecolor\* parameter'):
rb = widgets.RadioButtons(ax, ['tea', 'coffee'], activecolor='red',
radio_props={'facecolor': 'green'})
# *radio_props*' facecolor wins over *activecolor*
assert mcolors.same_color(rb._buttons.get_facecolor(), ['green', 'none'])


@check_figures_equal(extensions=['png'])
def test_radio_buttons_activecolor_change(fig_test, fig_ref):
widgets.RadioButtons(fig_ref.subplots(), ['tea', 'coffee'],
activecolor='green')

# Test property setter.
cb = widgets.RadioButtons(fig_test.subplots(), ['tea', 'coffee'],
activecolor='red')
cb.activecolor = 'green'


@check_figures_equal(extensions=["png"])
def test_check_buttons(fig_test, fig_ref):
widgets.CheckButtons(fig_test.subplots(), ["tea", "coffee"], [True, True])
Expand All @@ -1031,6 +1083,29 @@ def test_check_buttons(fig_test, fig_ref):
ax.text(.25, 1/3, "coffee", transform=ax.transAxes, va="center")


@check_figures_equal(extensions=['png'])
def test_check_button_props(fig_test, fig_ref):
label_props = {'color': ['red'], 'fontsize': [24]}
frame_props = {'facecolor': 'green', 'edgecolor': 'blue', 'linewidth': 2}
check_props = {'facecolor': 'red', 'linewidth': 2}

widgets.CheckButtons(fig_ref.subplots(), ['tea', 'coffee'], [True, True],
label_props=label_props, frame_props=frame_props,
check_props=check_props)

cb = widgets.CheckButtons(fig_test.subplots(), ['tea', 'coffee'],
[True, True])
cb.set_label_props(label_props)
# Setting the label size automatically increases default marker size, so we
# need to do that here as well.
cb.set_frame_props({**frame_props, 's': (24 / 2)**2})
# FIXME: Axes.scatter promotes facecolor to edgecolor on unfilled markers,
# but Collection.update doesn't do that (it forgot the marker already).
# This means we cannot pass facecolor to both setters directly.
check_props['edgecolor'] = check_props.pop('facecolor')
cb.set_check_props({**check_props, 's': (24 / 2)**2})


@check_figures_equal(extensions=["png"])
def test_check_buttons_rectangles(fig_test, fig_ref):
# Test should be removed once .rectangles is removed
Expand Down
Loading