Matplotlib 依赖的滑块 [英] Matplotlib dependent sliders

查看:25
本文介绍了Matplotlib 依赖的滑块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过选择权重来选择三角形的一个点.这应该通过控制 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.如何创建比此 slidermax 选项更复杂的依赖项?

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"很容易.唯一的要求是 sliderminslidermax 有一个 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆