Widgets for interactive notebooks.¶
Widgets are a quick way to get interactivity in your Jupyter displays. They include graphical user interface tools like sliders, check boxes, and more.
Jupyter has its own version of widgets, based on Python widgets. We use the interact command to access them.
We do a simple import to access the interact tool for widgets.
from ipywidgets import interact
First we define a simple function that the widgets will activate.
def f(x):
return x
Next, we create the widgets by calling the interact function, using an argument type for x.
The choice of x will give us sliders with integer or float values, check boxes, or text entry boxes. You can try each of the following:
interact(f,x=(0,10));
interact(f,x=(0.0,10.0));
interact(f,x=True);
interact(f,x='Hello World');
Example 1. Interactive plottnig¶
Let’s use these ideas to get some interaction in our plots.
First we load in the modules we need for plotting.
%matplotlib inline
from numpy import *
from matplotlib.pyplot import *
Next, we define a function that will be called by our widget. All it does is plot the function \($y = x^k\)$ with a choice for the power \(k\) set by the widget.
def update(k=1):
plot(x,x**k)
Now we define the range of x values, and call up the widget using the interact command. Notice the function “update” defined above is used in the interact command.
Run the following, and you will have an interactive plot.
x=linspace(0,1)
interact(update,k=(1,10));
Example 2. Widget with a built-in function¶
We can get fancy with Python, using the lambda notation to implicitly define a function that works like “update” above, without having to write a separate def command. Try this:
x=linspace(0,1)
interact(lambda k: plot(x,x**k),k=(1,10));
Example 3. Translates of the sin function¶
Just for fun, we try translating a function interactively. We are plotting the trig function \($y = \sin(x-k)\)$ for various values of the translate k.
For clarity, we mark the location of k on the plot and see how it tracks the zero crossing of the sine function.
x=linspace(0,4*pi)
interact(lambda k: plot(x,sin(x-k),k,0,'o'),k=(0,10));
Example 4¶
It is worth noting that sometimes there is a lag between when you move the slider, and when the plot updates. You can read more about how to deal with this online, on the Python notes about widgets.
Here is an example based on Example 3 above, where you can see the lag. The lag comes because the widget is producing many floating point values as it moves. The plotting routine has a hard time keeping up.
Notice also that we define the sinupdate function separately, in order to get rid of that ugly text under graph that appeared in Example 3.
def sinupdate(k=0):
plot(x,sin(x-k),k,0,'o')
x=linspace(0,4*pi)
interact(sinupdate,k=(0.0,10.0));