Calmcode - ipywidgets: components

Components

1 2 3 4 5 6 7 8

Instead of making a single component for a single chart, we can also make several ipywidgets components. The code below demonstrates multiple components that listen to a slider.

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

p = widgets.FloatSlider(
    value=0.02,
    min=0.01,
    max=0.20,
    step=0.001,
    description='$$p$$',
    readout=True,
    readout_format='.3f',
)

html = widgets.HTMLMath(
    value=f"Let's play around with the following formula: <br> $$np(1-p)^2$$",
)

def f(p):
    n = np.linspace(1, 100, 100)
    plt.plot(n, n*0.02*(1-0.02)**n, label="p=0.02");
    plt.plot(n, n*p*(1-p)**n, label=f"p={np.round(p, 3)}");
    plt.legend()

out = widgets.interactive_output(f, {'p': p})

widgets.VBox([html, p, out])