Displaying Radio buttons horizontally in matplotlib

2024/9/19 20:39:35

I am using the matplotlib.widgets to create radio buttons in my widgets, the buttons coming are stacked vertically, I would like them to be stacked horizontally.

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()

As you can see with this example you can get the radio buttons like this Plot with radio buttons stacked vertically,

I am wondering is there a way to stack these radio buttons horizontally.

Answer

There is currently an attempt to introduce an orientation argument to RadioButtons in PR #13374; this has not yet been finalized.

As I had commented in this PR, an alternative option would be to use a scatter plot for the buttons. The following shows how I would imagine this implementation. There are two main enhancements compared to the usual buttons:

  • Radio buttons are always round independent of the size of the axes.
  • They can be aligned arbitrarily, in particular horizontally.

This is achieved by creating a legend internally, which has all the required options readily available. Any valid arguments to Legend can be used for the Buttons as well.

import matplotlib.pyplot as plt
from matplotlib.widgets import AxesWidget, RadioButtonsclass 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 strThe button labels.active : intThe index of the initially selected button.activecolor : colorThe color of the selected button.size : floatSize of the radio buttonsorientation : strThe orientation of the buttons: 'vertical' (default), or 'horizontal'.Further parameters are passed on to `Legend`."""AxesWidget.__init__(self, ax)self.activecolor = activecoloraxcolor = ax.get_facecolor()self.value_selected = Noneax.set_xticks([])ax.set_yticks([])ax.set_navigate(False)circles = []for i, label in enumerate(labels):if i == active:self.value_selected = labelfacecolor = activecolorelse:facecolor = axcolorp = 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.textsself.circles = self.box.legendHandlesfor c in self.circles:c.set_picker(5)self.cnt = 0self.observers = {}self.connect_event('pick_event', self._clicked)def _clicked(self, event):if (self.ignore(event) or event.mouseevent.button != 1 orevent.mouseevent.inaxes != self.ax):returnif event.artist in self.circles:self.set_active(self.circles.index(event.artist))

Use it as

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()

enter image description here

Or

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

enter image description here

https://en.xdnf.cn/q/72526.html

Related Q&A

Python MemoryError on large array

This is the python script that Im trying to run:n = 50000000000 ##50 billion b = [0]*n for x in range(0,n):b[x] = random.randint(1,899999)... But the output Im getting is:E:\python\> python sort.py…

How to generate a PDF with non-ascii characters using from_string from python-pdfkit

Im struggling to generate just a simple PDF with non-ascii characters using Python 3.5.2, python-pdfkit and wkhtmltox-0.12.2.This is the easiest example I could write:import pdfkit html_content = u<…

Minimum window of days required to travel all cities

This is an interesting question that I came across in a coding challenge:There are k cities and n days. A travel agent is going to show you city k on day n. Youre supposed to find the minimum number of…

Force Nosetests to Use Python 2.7 instead of 3.4

Ive been learning Python using version 3.4. I recently started learning Web.py so have been using Python 2.7 for that, since web.py not supported in Python 3.4. I have nose 1.3.4 module installed for …

Python regex not to match http://

I am facing a problem to match and replace certain words, not contained in http:// Present Regex: http://.*?\s+This matches the pattern http://www.egg1.com http://www.egg2.com I need a regex to matc…

how can I maintain sequence of my list using set?

In [1]: l1 = [a,2,3,0,9.0,0,2,6,b,a]In [2]: l2 = list(set(l1))In [3]: l2 Out[3]: [a, 0, 2, 3, 6, 9.0, b]Here you can see the the list l2 is falling with different sequence then the original l1, I need …

How to reference a dict object?

I have a Python dict object d. d = {a: 1, b: 2, c: 3}. My problem is really simple. I want to reference a variable to the elements of d. For example, something like:In[1]: p = d[a] >>> p = 1 I…

Python 3.3: DeprecationWarning when using nose.tools.assert_equals

I am using nosetest tools for asserting a python unittest:... from nose.tools import assert_equals, assert_almost_equalclass TestPolycircles(unittest.TestCase):def setUp(self):self.latitude = 32.074322…

Panel/Hvplot interaction when variable is changing

Im trying to create a dashboard with two holoviews objects: a panel pn.widgets.Select object that contains a list of xarray variables, and a hvplot object that takes the selected variable on input, lik…

asyncio matplotlib show() still freezes program

I wish to run a simulation while at the same time output its progress in a plot. Ive been looking through a lot of examples of threading and multiprocessing, but they are all pretty complex. So I thoug…