Calmcode - ipywidgets: all together

All Together

1 2 3 4 5 6 7 8

Let's look at a larger set of components and how they link up.

import numpy as np
import matplotlib.pylab as plt
import ipywidgets as widgets

slider_mu = widgets.FloatSlider(
    value=5,
    min=0,
    max=10,
    step=0.1,
    description='$$\mu$$'
)
slider_sigma = widgets.FloatSlider(
    value=5,
    min=0,
    max=3,
    step=0.1,
    description='$$\sigma$$'
)

btn = widgets.Button(
    description='Run',
    icon='check'
)

out = widgets.Output()

def on_button_clicked(b):
    with out:
        out.clear_output()
        x1 = np.random.normal(0.0, 1.0, 10_000_000)
        x2 = np.random.normal(slider_mu.value, slider_sigma.value, 10_000_000)
        plt.hist(x1, bins=30, label="standard", alpha=0.6)
        plt.hist(x2, bins=30, label="new", alpha=0.6)
        plt.legend()
        plt.show()

btn.on_click(on_button_clicked)

sliders = widgets.VBox([slider_mu, slider_sigma, btn])
widgets.HBox([sliders, out])

Note how the button-click now listens to a lot of components and is able to target the out component via the on_button_clicked function.