Matplotlib dependent sliders

对着背影说爱祢 提交于 2020-01-23 13:20:07

问题


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.

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 requires a type Slider, not integer. How can I create dependencies a little more complex than this slidermax option?


回答1:


@ubuntu's answer is the simple way.

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

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


来源:https://stackoverflow.com/questions/20751144/matplotlib-dependent-sliders

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!