Jupyter 5: Widgets
Since we’re typically running our notebooks in a web browser, they are quite well suited for also including more interactive elements. A typical use case could be that you want to communicate some results to a collaborator or to a wider audience, and that you would like them to be able to modify how the results are displayed. It could, for example, be to select which gene to plot for, or to see how some parameter value affects a clustering. Jupyter notebooks has great support for this in the form of widgets.
Widgets are eventful Python objects that have a representation in the
browser, often as a control like a slider, textbox, etc. These are
implemented in the ipywidgets
package.
The easiest way to get started with using widgets are via the
interact
and interactive
functions. These
functions autogenerate widgets from functions that you define, and then
call those functions when you manipulate the widgets. Too abstract?
Let’s put it into practice!
Let’s try to add sliders that allow us to change the frequency, amplitude and phase of the sine curve we plotted previously.
# Import the interactive function from ipywidgets
from ipywidgets import interactive
# Also import numpy (for calculating the sine curve)
# and pyplot from matplotlib for plotting
import numpy as np
import matplotlib.pyplot as plt
# Define the function for plotting the sine curve
def sine_curve(A, f, p):
# Set up the plot
1, figsize=(4,4))
plt.figure(# Create a range of 100 evenly spaced numbers between 0 and 100
= np.linspace(0,10,100)
x # Calculate the y values using the supplied parameters
= A*np.sin(x*f+p)
y # Plot the x and y values ('r-' specifies color and line style)
='red', linestyle="-")
plt.plot(x, y, color
plt.show()
# Here we supply the sine_curve function to interactive,
# and set some limits on the input parameters
= interactive(sine_curve,
interactive_plot =(1, 5, 1),
A=(0, 5, 1),
f=(1, 5, 0.5))
p
# Display the widgets and the plot
interactive_plot
The code above defines a function called sine_curve
which takes three arguments:
A
= the amplitude of the curvef
= the frequency of the curvep
= the phase of the curve
The function creates a plot area, generates x-values and calculates
y-values using the np.sin
function and the supplied
parameters. Finally, the x and y values are plotted.
Below the function definition we use interactive
with
the sine_curve
function as the first parameter. This means
that the widgets will be tied to the sine_curve
function.
As you can see we also supply the A
, f
and
p
keyword arguments. Importantly, all parameters defined in
the sine_curve
function must be given in the
interactive
call and a widget is created for each one.
Depending on the type
of the passed argument different
types of widgets will be created by interactive
. For
instance:
int
orfloat
arguments will generate a sliderbool
arguments (True/False) will generate checkbox widgetslist
arguments will generate a dropdownstr
arguments will generate a text-box
By supplying the arguments in the form of tuples
Links to an external site.
we can adjust the properties of the sliders. f=(1, 5, 1)
creates a widget with minimum value of 1
, maximum value of
5
and a step size of 1
. Try adjusting these
numbers in the interactive
call to see how the sliders
change (you have to re-execute the cell).
The final line of the cell (interactive_plot
) is where
the actual widgets and plot are displayed. This code can be put in a
separate cell, so that you can define functions and widgets in one part
of your notebook, and reuse them somewhere else.
This is how it should look if everything works. You can now set the frequency amplitude and phase of the sine curve by moving the sliders.
There are lots of widgets, e.g.:
- Dropdown menus
- Toggle buttons
- Range sliders
- File uploader
… and much, much more. Here is a list
of all available widgets
Links to an external site. together with documentation and examples.
Some of these widgets cannot be autogenerated by
interactive
, but fear not! Instead of relying on
autogeneration we can define the widget and supply it directly to
interactive
.
To see this in practice, change out the A
argument to a
pre-defined IntSlider
widget. First define the slider:
from ipywidgets import widgets
= widgets.IntSlider(value=2, min=1, max=5, step=1) A
Then replace the call to interactive
so that it looks
like this:
= interactive(sine_curve, A=A, f=5, p=5) interactive_plot
Extra challenge
If you can’t get enough of widgets you might want to try this out:
see if you can figure out how to add a widget that lets you pick the
color for the sine curve line. Search for the appropriate widget in the
Widget
list
Links to an external site.. You’ll need to update the sine_curve
function and
pass the new widget as an argument in the call to
interactive
. If you need help, see the code chunk
below:
Click to show
# Import the interactive function from ipywidgets
from ipywidgets import interactive
# Also import numpy (for calculating the sine curve)
# and pyplot from matplotlib for plotting
import numpy as np
from ipywidgets import widgets ## <- import widgets
import matplotlib.pyplot as plt
# Define the function for plotting the sine curve
def sine_curve(A, f, p, color): ## <- add parameter here
# Set up the plot
1, figsize=(4,4))
plt.figure(# Create a range of 100 evenly spaced numbers between 0 and 100
= np.linspace(0,10,100)
x # Calculate the y values using the supplied parameters
= A*np.sin(x*f+p)
y # Plot the x and y values
=color) ## <- Use color from widget here
plt.plot(x, y, color
plt.show()
# Here we supply the sine_curve function to interactive,
# and set some limits on the input parameters
# Define the colorpicker widget
= widgets.ColorPicker(description='color',value="red")
colorpicker = interactive(sine_curve,
interactive_plot =(1, 5, 1),
A=(0, 5, 1),
f=(1, 5, 0.5),
p=colorpicker) ## <- Supply the colorpicker to the function
color
# Display the widgets and the plot
interactive_plot
Attention!
Note that you may have to close the color picker once you’ve made your choice in order to make the plot update.
Other interactive plots
Jupyter widgets, like we used here, is the most vanilla way of getting interactive graphs in Jupyter notebooks. Some other alternatives are:
- Plotly Links to an external site. is actually an API to a web service that renders your graph and returns it for display in your Jupyter notebook. Generates very visually appealing graphs, but from a reproducibility perspective it’s maybe not a good idea to be so reliant on a third party.
- Bokeh Links to an external site. is another popular tool for interactive graphs. Most plotting packages for Python are built on top of matplotlib, but Bokeh has its own library. This can give a steeper learning curve if you’re used to the standard packages.
- mpld3 Links to an external site. tries to integrate matplotlib with Javascript and the D3js package. It doesn’t scale well for very large datasets, but it’s easy to use and works quite seamlessly.
Quick recap
In the three previous sections we’ve learned:
- How to implement interactive widgets in notebooks