Rubenulis
Rubenulis

Reputation: 1768

Obtaining matplotlib slider widget position from callback in non-global context

I wanted to use the matplotlib slider as seen in an example from a previous question (below) inside a GUI window (such as TkInter etc). But, in a non-global context, the variables for the plot ("spos, fig, ax") are not defined. My understanding is that because update is used as a callback function, one can't or shouldn't pass arguments.

If so, how can a plot be updated without global variables? or

How can I obtain the slider position outside the callback function?

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider

fig, ax = plt.subplots()
plt.subplots_adjust(bottom=0.25)

t = np.arange(0.0, 100.0, 0.1)
s = np.sin(2*np.pi*t)
l, = plt.plot(t,s)
plt.axis([0, 10, -1, 1])

axcolor = 'lightgoldenrodyellow'
axpos = plt.axes([0.2, 0.1, 0.65, 0.03], axisbg=axcolor)

spos = Slider(axpos, 'Pos', 0.1, 90.0)

def update(val):
    pos = spos.val
    ax.axis([pos,pos+10,-1,1])
    fig.canvas.draw_idle()

spos.on_changed(update)

plt.show()

Related:

1) Another related question seems to cover this topic but does not seem to address how the position of the slider is obtained.

2) A similar question was asked and solved with Slider.set_val(). It seems in my case I would need Slider.get_val() instead.

Upvotes: 0

Views: 708

Answers (1)

J.J. Hakala
J.J. Hakala

Reputation: 6214

It is possible to pass more arguments to the callback function, for example with functools.partial

def update(data, val):
    pos = spos.val

    ax.axis([pos,pos+10,-1,1])
    fig.canvas.draw_idle()

    data['position'] = pos

import functools
data = dict()
spos.on_changed(functools.partial(update, data))

plt.show()

try:
    print data['position']
except KeyError:
    pass

A class with __call__ method could also be used as a callback.

Upvotes: 1

Related Questions