Matplotlib Updating slider widget range

给你一囗甜甜゛ 提交于 2019-11-28 12:38:46

It looks like the slider does not have a way to update the range (api). I would suggest setting the range of the slider to be [0,1] and doing

frame = int(self.nframes * value)

On a somewhat related note, I would have made frame an instance variable a data attribute instead of a global variable (tutorial).

In order to update a slider range you may set the min and max value of it directly,

slider.valmin = 3
slider.valmax = 7

In order to reflect this change in the slider axes you need to set the limits of the axes,

slider.ax.set_xlim(slider.valmin,slider.valmax)

A complete example, where typing in any digit changes the valmin of the slider to that value.

import matplotlib.pyplot as plt
import matplotlib.widgets

fig, (ax,sliderax) = plt.subplots(nrows=2,gridspec_kw=dict(height_ratios=[1,.05]))

ax.plot(range(11))
ax.set_xlim(5,None)
ax.set_title("Type number to set minimum slider value")
def update_range(val):
    ax.set_xlim(val,None)

def update_slider(evt):
    print(evt.key)
    try:
        val = int(evt.key)
        slider.valmin = val
        slider.ax.set_xlim(slider.valmin,None)
        if val > slider.val:
            slider.val=val
            update_range(val)
        fig.canvas.draw_idle()
    except:
        pass

slider=matplotlib.widgets.Slider(sliderax,"xlim",0,10,5)
slider.on_changed(update_range)

fig.canvas.mpl_connect('key_press_event', update_slider)

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