Matplotlib依赖的滑块 [英] Matplotlib dependent sliders
问题描述
我想通过选择权重来选择三角形的一个点.这应该通过控制 2 个滑块 (matplotlib.widgets.Slider
) 来完成.这两个滑块表示定义点的三个权重中的两个.第三个权重很容易计算为 1.0 - slider1 - slider2
.
I want to choose a point of a triangle by choosing its weights. This should be done by controlling 2 Sliders (matplotlib.widgets.Slider
). These two sliders express two out of three weights that define the point. The third weight is easily calculated as 1.0 - slider1 - slider2
.
现在很明显,所有权重的总和应等于1.0,因此不可能选择0.8和0.9作为两个滑块的值.参数 slidermax
允许使滑块依赖,但我不能说:
Now it is clear that the sum of all weights should be equal to 1.0, so choosing 0.8 and 0.9 as the values for the two sliders should be impossible. The argument slidermax
allows to make sliders dependent, but I can not say:
slider2 = Slider(... , slidermax = 1.0-slider1)
slidermax
需要类型 Slider
,而不是 integer
.如何创建比此lidermax选项稍微复杂一点的依赖项?
slidermax
requires a type Slider
, not integer
.
How can I create dependencies a little more complex than this slidermax option?
推荐答案
@ubuntu 的答案很简单.
@ubuntu's answer is the simple way.
另一种选择是将 Slider
子类化,以完全满足您的需求.这将是最灵活的(您甚至可以让滑块相互更新,而它们目前还没有这样做).
Another option is to subclass Slider
to do exactly what you want. This would be the most flexible (and you could even make the sliders update each other, which they currently don't do).
但是,在这种情况下,很容易使用"ducktyping".唯一的要求是 slidermin
和 slidermax
具有 val
属性.它们实际上不必是 Slider
的实例.
However, it's easy to use "ducktyping" in this case. The only requirement is that slidermin
and slidermax
have a val
attribute. They don't actually have to be instances of Slider
.
考虑到这一点,您可以执行以下操作:
With that in mind, you could do something like:
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
class FakeSlider(object):
def __init__(self, slider, func):
self.func, self.slider = func, slider
@property
def val(self):
return self.func(self.slider.val)
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.25)
sliderax1 = fig.add_axes([0.15, 0.1, 0.75, 0.03], axisbg='gray')
sliderax2 = fig.add_axes([0.15, 0.15, 0.75, 0.03], axisbg='gray')
slider1 = Slider(sliderax1, 'Value 1', 0.1, 5, valinit=2)
slider2 = Slider(sliderax2, 'Value 2', -4, 0.9, valinit=-3,
slidermax=FakeSlider(slider1, lambda x: 1 - x))
plt.show()
这篇关于Matplotlib依赖的滑块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!