簡體   English   中英

在 matplotlib 中水平顯示單選按鈕

[英]Displaying Radio buttons horizontally in matplotlib

我正在使用matplotlib.widgets在我的小部件中創建單選按鈕,即將出現的按鈕垂直堆疊,我希望它們水平堆疊。

MVCE:

import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
plt.subplots_adjust(left=0.2)
rax = plt.axes([0.5,0.05,0.1,0.1])
radio =  RadioButtons(rax ,['1','2','3'], active=0, activecolor='blue' )
plt.show()

正如您在這個示例中看到的那樣,您可以獲得這樣的單選按鈕使用垂直堆疊的單選按鈕繪圖 ,

我想知道有沒有辦法水平堆疊這些單選按鈕。

當前正在嘗試向PR#13374中的 RadioButtons引入orientation參數。 尚未完成。

正如我在此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)

在此處輸入圖片說明

由於 stackexchange 不希望將此作為編輯,因此這是來自 @ImportanceOfBeingErnest 的上述答案的更新版本,適用於最新的 matplotlib 版本(例如 >= v3.3)

import matplotlib.pyplot as plt
from matplotlib.widgets import AxesWidget, RadioButtons
from matplotlib import cbook

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._observers = cbook.CallbackRegistry()
        
        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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM