Contextmanager for Controls object#

When you are making a complex interactive visualization you may need to use many mpl-interactions functions. One way to do this is to pass controls=controls to every function you call. But that’s pretty lame because you have to type the same thing out many times. So you can also use controls objects as context managers:

%matplotlib ipympl

Using all params#

If you want to use all the parameters in a controls object then you can simply do:

with controls:
    # iplt functions here

Using only a subset of the control’s params#

You can also use a subset of the params in a context by indexing it with strings.


with controls['param-name', 'param-name-2',...]:
    # iplt functions here

Adding new params from within a context#

You can still add new params from within a controls context:

with controls:
    iplt.plot(x,f, new_param=np.linspace(0, 1))

Example#

Here is an example that demonstrates the various possible behaviors

import matplotlib.pyplot as plt
import numpy as np

import mpl_interactions.ipyplot as iplt

x = np.linspace(0, 2 * np.pi, 1000)
tau = np.linspace(5, 10)
beta = np.linspace(0.25, 1)
delta = np.linspace(0, 0.75)
fig, ax = plt.subplots()


def f1(tau, beta):
    return np.sin(x * tau) * x * beta


def f2(tau, beta):
    return np.sin(x * beta) * x * tau


def f2_tau(tau):
    return np.sin(x * 1) * x * tau


def f2_tau_delta(tau, delta):
    return np.sin(x * delta) * x * tau


# Create the initial object
controls = iplt.plot(f1, "k--", tau=tau, beta=beta, label="f1")

# context with all parameters
with controls:
    iplt.plot(f2, label="f2")

# adding a new parameter and excluding beta
with controls["tau"]:
    iplt.plot(f2_tau_delta, delta=delta, label="f2 tau alpha")

# excluding all params except tau
with controls["tau"]:
    iplt.plot(f2_tau, label="f2 only tau")

_ = plt.legend()