目前正在尝试在PR #13374orientation
中引入参数;这尚未最终确定。RadioButtons
正如我在此 PR 中所评论的,另一种选择是对按钮使用散点图。下面展示了我如何想象这个实现。与通常的按钮相比,有两个主要增强功能:
- 单选按钮总是圆形的,与轴的大小无关。
- 它们可以任意排列,尤其是水平排列。
这是通过在内部创建一个图例来实现的,该图例具有所有必需的选项。任何有效Legend
的参数也可以用于按钮。
import matplotlib.pyplot as plt
from matplotlib.widgets import AxesWidget, RadioButtons
class MyRadioButtons(RadioButtons):
def __init__(self, ax, labels, active=0, activecolor='blue', size=49,
orientation="vertical", **kwargs):
"""
Add radio buttons to an `~.axes.Axes`.
Parameters
----------
ax : `~matplotlib.axes.Axes`
The axes to add the buttons to.
labels : list of str
The button labels.
active : int
The index of the initially selected button.
activecolor : color
The color of the selected button.
size : float
Size of the radio buttons
orientation : str
The orientation of the buttons: 'vertical' (default), or 'horizontal'.
Further parameters are passed on to `Legend`.
"""
AxesWidget.__init__(self, ax)
self.activecolor = activecolor
axcolor = ax.get_facecolor()
self.value_selected = None
ax.set_xticks([])
ax.set_yticks([])
ax.set_navigate(False)
circles = []
for i, label in enumerate(labels):
if i == active:
self.value_selected = label
facecolor = activecolor
else:
facecolor = axcolor
p = ax.scatter([],[], s=size, marker="o", edgecolor='black',
facecolor=facecolor)
circles.append(p)
if orientation == "horizontal":
kwargs.update(ncol=len(labels), mode="expand")
kwargs.setdefault("frameon", False)
self.box = ax.legend(circles, labels, loc="center", **kwargs)
self.labels = self.box.texts
self.circles = self.box.legendHandles
for c in self.circles:
c.set_picker(5)
self.cnt = 0
self.observers = {}
self.connect_event('pick_event', self._clicked)
def _clicked(self, event):
if (self.ignore(event) or event.mouseevent.button != 1 or
event.mouseevent.inaxes != self.ax):
return
if event.artist in self.circles:
self.set_active(self.circles.index(event.artist))
用它作为
plt.subplots_adjust(left=0.2)
rax = plt.axes([0.5,0.05,0.4,0.07])
radio = MyRadioButtons(rax ,['1','2','3'], active=0, activecolor='crimson',
orientation="horizontal")
plt.show()

或者
rax = plt.axes([0.2,0.5,0.25,0.1])
radio = MyRadioButtons(rax ,["AA", "BB", "CC", "DD"], ncol=2)
