As well as supporting interactive content editing and code execution, Jupyter notebooks also allow the embedding of interactive widgets that can be used to develop simple interactive user interfaces within a notebook.
In Python notebooks, the ipywidgets
package provides all we need to get started.
ipywidgets
¶#Enable inline charts
%matplotlib inline
#Import ipywidget functions
from ipywidgets import interact
import numpy as np
import pandas as pd
Let's create a simple sinusoidal dataset:
df=pd.DataFrame({'x':np.arange(10, step=0.01)})
df['y']=np.sin(df['x'])
df.plot(x='x',y='y');
We can create a function to calculate a similar wave with a frequency parameter.
def sine_wave(f=1):
df=pd.DataFrame({'x':np.arange(10, step=0.01)})
df['y']=np.sin(f * df['x'])
df.plot(x='x',y='y');
sine_wave(5)
If we "decorate" the sine wave function appropriately, we can automatically generate an interactive control to set the frequency value:
@interact(freq = 1)
def sine_wave(freq =1):
''' Plot a simple sine wave. '''
df = pd.DataFrame({'x':np.arange(10, step=0.01)})
df['y'] = np.sin(freq * df['x'])
df.plot(x='x',y='y');
A Jupyter Widget
We can achieve more control over the slider if we need it, such as setting the upper and lower value limits and the step size.
We can also invoke other widget types. For example, if we pass a list of colour values, we can generate a drop down list to select the line colour. Or a boolean value for a checkbox.
@interact(freq = (1,5,1),
dashed = True,
col = ['red','blue', 'green']
)
def sine_wave(freq, col, dashed):
''' Plot a simple sine wave using with specified style. '''
df = pd.DataFrame({'x':np.arange(10, step=0.01)})
df['y'] = np.sin(freq * df['x'])
df.plot(x='x',y='y', color=col, style = '--' if dashed else '-');
A Jupyter Widget
#ish via https://github.com/jupyter-widgets/ipywidgets/issues/1582
from IPython.display import display
import numpy as np
from ipywidgets import interactive_output
import matplotlib.pyplot as plt
def plot_oscillation(wavelength, magnitude, phase):
x = np.linspace(-20, 20, 1000)
plt.plot(x, magnitude*np.sin((x+phase)/(wavelength/(2*np.pi))))
plt.ylim((-10,10))
plt.show()
w = dict(wavelength = FloatSlider(2*np.pi, min=0.1, max=20, step=0.1, description='wavelength'),
magnitude = FloatSlider(1, min=0.1, max=10, step=0.1, description='magnitude'),
phase = FloatSlider(0, min=0, max=10, step=0.1, description='phase'))
#We can control elements of the layout
output = interactive_output(plot_oscillation, w)
box = HBox([VBox([*w.values()]), output])
display(box)
HBox(children=(VBox(children=(FloatSlider(value=1.0, description='magnitude', max=10.0, min=0.1), FloatSlider(…