从matplotlib中的CheckButtons对象中检索选定的值 [英] Retrieving the selected values from a CheckButtons object in matplotlib
问题描述
我有两个 CheckButtons 小部件,每个小部件有 3 个元素.I'd like to read the status of both widgets when either one of the CheckButtons is selected then update the chart accordingly.
I have two CheckButtons widgets with 3 elements each. I'd like to read the status of both widgets when either one of the CheckButtons is selected then update the chart accordingly.
滑块小部件具有用于返回滑块状态的 .val
,但是CheckButtons小部件似乎更尴尬(或者我缺少明显的东西)?
The slider widget has a .val
for returning the status of a slider, but the CheckButtons widget seems a bit more awkward (or am I missing something obvious)?
简短示例:
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
class Example:
def updateChart(self, event):
colour = self.colours.labels # gets labes as text object, is there an easy way of getting the status?
print colour
# measurement = measurements.something
def __init__(self):
colourax = plt.axes([0.5, 0.4, 0.09, 0.2])
measurementax = plt.axes([0.5, 0.6, 0.09, 0.2])
self.colours = CheckButtons(colourax, ('Red', 'Green', 'Blue'), (False, False, False))
self.measurements = CheckButtons(measurementax, ('1', '2', '3'), (False, False, False))
self.colours.on_clicked(self.updateChart)
self.measurements.on_clicked(self.updateChart)
def run(self):
plt.show()
ex = Example()
ex.run()
推荐答案
也许有更优雅的方法,但您始终可以自己跟踪每个复选框的状态,例如在 dict
中.您使用 on_clicked()
指定的函数将接收活动复选框的标签字符串作为其第二个参数,然后您可以使用它来适当地更新状态:
There might perhaps be a more elegant way but you can always keep track of the states of each of the checkboxes yourself, e.g. in a dict
. The function that you specify using on_clicked()
will receive the label string of the active checkbox as its second argument, which you can then use to update the status appropriately:
import matplotlib.pyplot as plt
from matplotlib.widgets import CheckButtons
class Example:
def onColor(self,label):
self.cstates[label] = not self.cstates[label]
print 'un'*(not self.cstates[label]) + 'checked %s' %label
self.updateChart()
def onMeasurement(self,label):
self.mstates[label] = not self.mstates[label]
print 'un'*(not self.mstates[label]) + 'checked %s' %label
self.updateChart()
def updateChart(self, event=None):
"""do something here using self.cstates and self.mstates?"""
pass
def __init__(self):
colourax = plt.axes([0.5, 0.4, 0.09, 0.2])
measurementax = plt.axes([0.5, 0.6, 0.09, 0.2])
clabels, cvals = ('Red', 'Green', 'Blue'), (False,)*3
mlabels, mvals = ('1', '2', '3'), (False,)*3
self.cstates = dict(zip(clabels,cvals))
self.mstates = dict(zip(mlabels,mvals))
self.colours = CheckButtons(colourax, clabels, cvals)
self.colours.on_clicked(self.onColor)
self.measurements = CheckButtons(measurementax, mlabels, mvals)
self.measurements.on_clicked(self.onMeasurement)
def run(self):
plt.show()
ex = Example()
ex.run()
不是最漂亮的,但很管用!
Not the prettiest, but it works!
这篇关于从matplotlib中的CheckButtons对象中检索选定的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!