单选框概述
单选框是图形化界面(GUI)中常见的控件,matplotlib中的单选框属于部件(widgets),matplotlib中的部件都是中性(neutral )的,即与具体后端实现无关。
单选框具体实现定义为matplotlib.widgets.RadioButtons类,继承关系为:Widget->AxesWidget->RadioButtons。
RadioButtons类的签名为class matplotlib.widgets.RadioButtons(ax, labels, active=0, activecolor='blue')
RadioButtons类构造函数的参数为:
ax:放置单选框的容器,类型为matplotlib.axes.Axes的实例。labels:单选框标签文本列表,类型为字符串列表。actives:单选框的初始选中按钮的索引,类型为整数,默认值为0。activecolor:按钮选中时的颜色,默认为蓝色。
RadioButtons类的属性为:
ax:放置按钮的容器,类型为matplotlib.axes.Axes的实例。labels:单选框文本列表。circles:单选框中的○图形对象,类型为patches.Circle列表。activecolor:单选框被选中时按钮的前景色。value_selected:被选中按钮的标签文本。
RadioButtons类最常用的方法为:
on_click(func):参数为回调函数,用于绑定单选框选中事件。set_active(index):根据单选框的索引切换选中/未选中状态。
案例:官方案例
https://matplotlib.org/gallery/widgets/radio_buttons.html
通过单选框选设置曲线颜色、线型。
代码分析
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
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(8*np.pi*t)
# 绘制曲线
fig, ax = plt.subplots()
l, = ax.plot(t, s0, lw=2, color='red')
plt.subplots_adjust(left=0.3

本文介绍Matplotlib中单选框组件的使用方法,包括如何创建单选框、设置样式及响应点击事件等。通过实例演示了如何利用单选框改变图表的样式。
最低0.47元/天 解锁文章
1748





