Revitalizing Jupyter Notebooks with Interactive Components: A Step-by-Step Guide to ipywidgets

Revitalizing Jupyter Notebooks with Interactive Components: A Step-by-Step Guide to ipywidgets

Traditionally, modifying output cells in a Jupyter notebook requires changing the underlying code and re-running the affected cells. This process can be cumbersome, inefficient, and error-prone, even for non-technical users. This is where ipywidgets come into play, enabling you to embed user-friendly interfaces that gather user input and display the impact of changes to data and results without requiring code interaction. In this article, we will explore how to create powerful dashboards using ipywidgets, starting with the basics and gradually developing a comprehensive example.

What is a Widget?

If you have experience creating graphical user interfaces (GUIs), you are likely familiar with the concept of widgets. A widget is a GUI element, such as a button, text box, or drop-down menu, that resides in the browser and allows users to control code and data in response to events. You can assemble and customize these GUI elements to create complex dashboards.

Some Popular Widgets

In this article, we will explore the practical applications of several widgets, including sliders, text boxes, and drop-down menus.

Getting Started with ipywidgets

To start using ipywidgets, you need to install the ipywidgets extension. If you use conda, enter the following command in your Terminal:

conda install -c conda-forge ipywidgets

For PIP users, the installation process is a two-step process:

pip install ipywidgets
jupyter nbextension enable --py widgetsnbextension

Adding a Widget to Your Notebook

To add a widget to your notebook, you must import the ipywidgets module:

import ipywidgets as widgets

Adding a Slider

To add a slider, define the minimum and maximum values, interval size (step), and initial value:

slider = widgets.IntSlider(
    min=0,
    max=10,
    step=1,
    description='Slider:',
    value=3
)

Displaying the Slider

To display the slider, use the display() function from the IPython.display module:

from IPython.display import display

display(slider)

Getting and Setting the Slider Value

To read the value of the slider, query its value property. Similarly, you can set the value of the slider:

print(slider.value)
slider.value = 5

Connecting Two Widgets

To synchronize the values of two widgets, use the jslink() function:

slider = widgets.IntSlider()
text = widgets.IntText()
display(slider, text)
widgets.jslink((slider, 'value'), (text, 'value'))

List of Widgets

To view the list of available widgets, use the dir() function:

print(dir(widgets))

Event Handling

Widgets can respond to events triggered by user interactions. A simple example is the click of a button, which triggers an action. Let’s see how this works:

btn = widgets.Button(description='Medium')
display(btn)

def btn_eventhandler(obj):
    print('Hello from the {} button!'.format(obj.description))

btn.on_click(btn_eventhandler)

Output Control

In this section, we will explore how to use widgets to control a Pandas dataframe. We will use the “Number of International Visitors to London” dataset, which shows the number of visitors to London in different years, quarters, purposes, times, modes, and nights.

Getting the Data

First, load the data into a Pandas dataframe:

import pandas as pd
import numpy as np

url = "https://data.london.gov.uk/download/number-international-visitors-london/b1e8f953-4c8a-4b45-95f5-e0d143d5641e/international-visitors-london-raw.csv"
df_london = pd.read_csv(url)

Filtering the Data

To filter the data by year, create a drop-down list with the unique values:

ALL = 'ALL'
def unique_sorted_values_plus_ALL(array):
    unique = array.unique().tolist()
    unique.sort()
    unique.insert(0, ALL)
    return unique

dropdown_year = widgets.Dropdown(options=unique_sorted_values_plus_ALL(df_london['year']))

Binding the Event Handler

To filter the data based on the selected value, create an event handler that will be called when the value of the pull-down menu changes:

def dropdown_year_eventhandler(change):
    if change.new == ALL:
        display(df_london)
    else:
        display(df_london[df_london['year'] == change.new])

dropdown_year.observe(dropdown_year_eventhandler, names='value')

Capturing the Output

To capture the output of the button and display it in a new cell, create a new instance of the output widget and display it in a new cell:

output_year = widgets.Output()
def dropdown_year_eventhandler(change):
    output_year.clear_output()
    with output_year:
        display(df_london[df_london['year'] == change.new])
display(output_year)

This is how it works! By using ipywidgets, you can create powerful dashboards that allow users to interact with your data and results in a user-friendly way.