Python Widgets
May 26, 2021
[1]: %matplotlib notebook
import ipywidgets as widgets
from IPython.display import display, clear_output
from ipywidgets import interact, interactive, interactive_output, fixed,␣
,→FloatRangeSlider, IntSlider, HBox, Layout, Output, VBox
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings('ignore')
[2]: def para(x, a, b, c):
return a*x**2 + b*x + c
[3]: fig, ax = plt.subplots(1, 1, figsize=(9.5, 5))
plt.subplots_adjust(left=0.05, bottom=None, right=1, top=None, wspace=None,␣
,→hspace=1.)
x = np.linspace(-5., 5., 100)
a = 1
b = 0
c = 0
#plot1
y_max = max(para(x, a, b, c))
line, = ax.plot(x, para(x, a, b, c),
'b-', lw=2)
#plot 1 params
ax.set_title('Parabolic Function: $f(x) = ax^2+bx+c$', fontsize=16)
ax.set_xlabel('$x$', fontsize=16)
ax.set_xlim(min(x), max(x))
ax.set_ylim(-y_max+10,y_max)
ax.grid(True)
plt.setp(ax.get_xticklabels(), fontsize=14)
plt.setp(ax.get_yticklabels(), fontsize=14)
1
#Define plot updater
def update(a,b,c):
line.set_ydata(para(x, a, b, c))
fig.canvas.draw_idle()
return
#Define control elements
s0=widgets.FloatSlider(
min=-10,
max=10.,
step=0.25,
value=1.0,
layout=Layout(width='500px'),
description='$a$',
style = {'description_width': 'initial'})
s1=widgets.FloatSlider(
min=-10,
max=10.,
step=0.25,
value=0.0,
layout=Layout(width='500px'),
description='$b$',
style = {'description_width': 'initial'})
s2=widgets.FloatSlider(
min=-10,
max=10,
step=0.25,
value=0.0,
layout=Layout(width='500px'),
description='$c$',
style = {'description_width': 'initial'})
#Connect controls to plot
out = interactive_output(update, {'a': s0, 'b': s1, 'c': s2})
#Set layout
Vbox_layout = Layout(display='flex', flex_flow='column',␣
,→justify_content='space-between', align_items='center')
#Display output
display(VBox([s0, s1, s2], layout=Vbox_layout))
2
<IPython.core.display.Javascript object>
<IPython.core.display.HTML object>
VBox(children=(FloatSlider(value=1.0, description='$a$', layout=Layout(width='500px'), max=10.0
[ ]: