Jupyter Snippet CB2nd 03_widgets
Jupyter Snippet CB2nd 03_widgets
3.3. Mastering widgets in the Jupyter Notebook
jupyter nbextension enable --py --sys-prefix widgetsnbextension
import ipywidgets as widgets
from ipywidgets import HBox, VBox
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display
%matplotlib inline
@widgets.interact
def f(x=5):
print(x)
@widgets.interact(x=(0, 5))
def f(x=5):
print(x)
@widgets.interact_manual(
color=['blue', 'red', 'green'], lw=(1., 10.))
def plot(freq=1., color='blue', lw=2, grid=True):
t = np.linspace(-1., +1., 1000)
fig, ax = plt.subplots(1, 1, figsize=(8, 6))
ax.plot(t, np.sin(2 * np.pi * freq * t),
lw=lw, color=color)
ax.grid(grid)
freq_slider = widgets.FloatSlider(
value=2.,
min=1.,
max=10.0,
step=0.1,
description='Frequency:',
readout_format='.1f',
)
freq_slider
range_slider = widgets.FloatRangeSlider(
value=[-1., +1.],
min=-5., max=+5., step=0.1,
description='xlim:',
readout_format='.1f',
)
range_slider
grid_button = widgets.ToggleButton(
value=False,
description='Grid',
icon='check'
)
grid_button
color_buttons = widgets.ToggleButtons(
options=['blue', 'red', 'green'],
description='Color:',
)
color_buttons
title_textbox = widgets.Text(
value='Hello World',
description='Title:',
)
title_textbox
color_picker = widgets.ColorPicker(
concise=True,
description='Background color:',
value='#efefef',
)
color_picker
button = widgets.Button(
description='Plot',
)
button
def plot2(b=None):
xlim = range_slider.value
freq = freq_slider.value
grid = grid_button.value
color = color_buttons.value
title = title_textbox.value
bgcolor = color_picker.value
t = np.linspace(xlim[0], xlim[1], 1000)
f, ax = plt.subplots(1, 1, figsize=(8, 6))
ax.plot(t, np.sin(2 * np.pi * freq * t),
color=color)
ax.grid(grid)
@button.on_click
def plot_on_click(b):
out.clear_output(wait=True)
with out:
plot2()
plt.show()
tab1 = VBox(children=[freq_slider,
range_slider,
])
tab2 = VBox(children=[color_buttons,
HBox(children=[title_textbox,
color_picker,
grid_button]),
])
out = widgets.Output()
tab = widgets.Tab(children=[tab1, tab2])
tab.set_title(0, 'plot')
tab.set_title(1, 'styling')
VBox(children=[tab, button, out])