Widgets for Interactivity
Using Widgets
Widgets are interactive objects on the notebook: buttons, check boxes, sliders and drop-down menus that allow the user to control actions in the notebook in a simple "point-and-click" method.
Widgets are a quick way to get interactivity in your Jupyter displays. You can read more about them here: Widget notes
Jupyter has its own version of widgets, based on iPython widgets. We use the interact command to access them.
Unfortunately, I can't seem to get this to show up in the Markdown files of this eBook. So you will have to experiment yourself in Jupyter, or read the reference above to see them live.
To get started, we import the interact function from the ipywidgets module.
Basic Structure
A widget is something you see on the computer screen that you click on, or move with the computer mouse, or enter text and data. It then does something.
The key is to define a function that that will do that "something."
Here is a really simple function, it just returns whatever is input to it.
Notice the argument of the function is called x. We will use this same x when calling up the interact command.
Next: We create the widgets by calling the interact function, using an argument type for x. The choice of type of data x will automatically select whether we get a slider, check box, text entry boxes, etc.
Here are a few examples. Note: It is useful to end the function call with a semicolon, to suppress useless output.
Using Widgets in Plotting
Now let's do some more interesting examples where we get the widget to plot something interesting.
We will import some utility functions for plotting and numerics.
The show command in the function is important, to get the plot to display.
Now we can the interact command using the update function, and a slider. Notice we use the argument k in this call, to match the k in the definition of function update above.
We can do more complex plots with many sliders. For instance, let's explore the sine funciton as it ofter appears in signal processing. It can have an amplitude, frequency and phase. We define the appropriate function and include sliders for this.
When we define the function, we can include some default values in the argument list.
When calling the interact function, makes sure the list of parameters have the same names as the action function plot_sine.
Other Graphics
You are not limited to simple 2D plots. The widgets can control more interesting graphics, as in this network example. This come from the site github.com/jupyter-widgets/ipywidgets
Last updated