Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib slider not working when called from a function

I have the following code, which shows a graph with a slinding bar

    from matplotlib.widgets import Slider
    import matplotlib.pyplot as plt
    from numpy import arange, sin, pi

    t = arange(0.0, 10.0, 0.01)

    fig =plt.figure(figsize = [30,20])
    ax = plt.subplot(111)
    plt.plot(t, sin(t*10))
    plt.ylim((-2,2))
    plt.xlim((0,1))
    plt.tight_layout()

    axzoom= plt.axes([0.15, 0.05, 0.65, 0.03])
    szoom = Slider(axzoom, 'Window', 1, 2)

    def update(val):
        ax.set_xlim([val,val+1])
        fig.canvas.draw_idle()
    szoom.on_changed(update)
    plt.show()

I want to call it from a function, that is:

def myplot(): 
    (... same code as above)

The problem is, when I do that the slinding bar does not work anymore. Any idea of what I could be doing wrong?

I am trying to execute it from iPython within Spyder. Thank you for any help.

like image 760
Sininho Avatar asked Mar 12 '23 10:03

Sininho


1 Answers

Based on this you need to keep the sliders around globally.

Your example would only need to be slightly adjusted:

def myplot(): 
    (... same code as above)
    return szoom

keep_sliders = myplot()
like image 152
Dunkelkoon Avatar answered Mar 15 '23 05:03

Dunkelkoon