Using Sliders to control scalar arguments#

There are often parameters to a matplotlib function that are Scalar. For example vmin, and vmax for imshow(), or x and y for axvline() and axhline(). These can be convenient to tie to the value of a single slider. While you can do this by making a function such as:

def f(*arg, **kwargs):
    return kwargs.pop('vmin', 0)

this can be a bit of hassle to do every time. So instead mpl_interactions does this for you when you pass an indexed Controls object or a tuple or other abbreviation to a scalar argument.

# %load_ext autoreload
%matplotlib ipympl

# %autoreload 2
import matplotlib.pyplot as plt
import numpy as np

from mpl_interactions import ipyplot as iplt
from mpl_interactions.controller import Controls  # import to make it easier to create

Setting the scalar parameter using a tuple#

You don’t need to pre-create the slider, you can do this directly in the function. Although then the name attached to the slider will be the same as the matplotlib argument.

So another way to get the same result as above is to do:

x = np.random.randn(20)
y = 2 * x + np.random.randn(20) / 2

fig, ax = plt.subplots()
ctrls = iplt.scatter(x, y, s=(10, 1000))

Setting Scalar parameters with an indexed controls#

You can also pass an indexed controls object directly to a scalar argument. This is a convenient way to link the same slider to multiple different functions.

x2 = np.random.randn(20)
y2 = -2 * x2 - np.random.randn(20) / 2

fig, ax = plt.subplots()
ctrls = iplt.scatter(x, y, s=(10, 1000))
_ = iplt.scatter(x2, y2, s=ctrls["s"])

Other names for the sliders#

If you create the slider to control the scalar by passing a tuple then the slider will always be named according to the matplotlib argument. For example, above the sliders were always named s. If you’d like to name them something else then you can precreate the slider.

Note that we need to explictl display the controls here because they will only be automatically displayed if they were created by an iplt function.

from mpl_interactions.controller import Controls

# create the controls object
ctrls = Controls(size=(10, 1000))

fig, ax = plt.subplots()
ctrls = iplt.scatter(x, y, s=ctrls["size"])
_ = iplt.scatter(x2, y2, s=ctrls["size"])

# ctrls.display()
# or when in a jupyter notebook