The Wayback Machine - https://web.archive.org/web/20241230170915/https://www.geeksforgeeks.org/understanding-jupyter-notebook-widgets/
Open In App

Understanding Jupyter Notebook Widgets

Last Updated : 18 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Jupyter Notebook Widgets help us create an interactive user interface in a Jupyter Notebook. Jupyter Widgets are interactive browser controls for Jupyter notebooks. Jupyter Notebook Widgets are collective items that can be added to Jupyter Notebooks to improve user knowledge by giving users the ability to handle and visualize data dynamically. In this article, we will learn about Jupyter Notebook Widgets and how to use them.

Jupyter Notebook Widgets

Jupyter Notebook widgets are interactive components or controls that allow users to interact with data and dynamically modify it in a Jupyter Notebook. They can be buttons, sliders, checkboxes, dropdown menus, text boxes, and more. Widgets enable users to create rich and responsive user interfaces in notebooks, making data exploration and analysis more intuitive and engaging.

Widgets

Widgets are interactive user interface elements that authorize user input in the same way that sliders, buttons, and text fields do.

Here are some related terms to widgets:

  • Ipywidgets Library - This library provides a range of Jupyter notebooks.
  • Widget Events - It contains multiple events, different tags, images, and videos, and keeps visitors informed about your schedule.
  • Wedget Container - Container "box" place: you can drag and drop other widgets, containing added containers, to arrange the layout of the screen. Containers allow you to Group content accompanying the same layout (style, position, etc.)
  • Widget Callbacks - Functions may contribute widgets to execute actions in response to user interactions.
  • Output widget - This is used to display dynamic content.

Widgets can be used to create a variety of user interfaces, from simple forms to complex dashboards. They can be used to interact with data, control the execution of code, and visualize results.

Here are some examples of how widgets can be used:

  • A slider can be used to adjust the threshold of a data filter.
  • A text box can be used to enter a search query.
  • A checkbox can be used to select or deselect a column in a data table.
  • A dropdown menu can be used to select a model to train.
  • A button can be used to submit a form or run a code cell.
  • A data table can be used to view and edit data.
  • A plot can be used to visualize the results of a machine learning model.

Types of Widgets

There are many different types of Jupyter Notebook widgets, each with its own functionality. Some of the most common types of widgets include:

  • Sliders: Sliders allow users to select a value from a continuous range.
  • Text boxes: Text boxes allow users to enter text.
  • Checkboxes: Checkboxes allow users to select or deselect an option.
  • Dropdown menus: Dropdown menus allow users to select an option from a list of options.
  • Buttons: Buttons allow users to perform actions, such as submitting a form or running a code cell.
  • Data tables: Data tables allow users to view and edit tabular data.
  • Plots: Plots allow users to visualize data in a variety of ways.
  • Media players: Media players allow users to play audio and video files.
  • Custom widgets: It is also possible to create custom widgets with specific functionality.

Installation and setup

Installing the Python ipywidgets package will automatically configure Jupyter Noteboook.

pip install ipywidgets

Import ipywidgets

import ipywidgets as widgets

Understanding Jupyter Notebook Widgets

Jupyter Notebook provides various types of widgets that you can use to create interactive elements in your notebook.

display widegts

The display means As an insider, the display function is a crucial part of making Jupyter Notebook widgets interactive.using this render,creating an interger slider as a below image.widgets are objects that show interactive user interface items, in the way that sliders, buttons, text recommendation fields, and output containers. To create these widgets visible and working in the notebook, you use the display function from the IPython IPython.display module to show and show the system.

Python3
import ipywidgets as widgets

from ipywidgets import IntSlider
import IPython.display as display

slider = IntSlider(value=5, min=0, max=10)
display.display(slider)

Output:

1

keys of Widgets

In addition to benefit, most widgets share keys, description, and disabled. To visualize the entire list of integrated, stateful characteristics of some specific widget, you can query the answers property.

.keys

Python3
slider = IntSlider(value=5, min=0, max=10, step = 1)

slider.keys

Output:

['_dom_classes',
'_model_module',
'_model_module_version',
'_model_name',
'_view_count',
'_view_module',
'_view_module_version',
'_view_name',
'behavior',
'continuous_update',
'description',
'description_allow_html',
'disabled',
'layout',
'max',
'min',
'orientation',
'readout',
'readout_format',
'step',
'style',
'tabbable',
'tooltip',
'value']

Text Widget

Text widgets allow users to input text or display information. You can use Text or Textarea widgets for single-line or multi-line text input, respectively.

Python3
widgets.Text(value ="Hello Geeksforgeek!")

Output:

Screenshot-2023-11-06-163058BoundedIntText widget

Python3
widgets.BoundedIntText(
value=7,
min=0,
max=1000,
step=3,
description='Geeksforgeek count:',
disabled=False
)

Output:

ezgif-1-113ee41622

ToggleButton

Python3
widgets.ToggleButton(
value=False,
description='Click me',
disabled=False,
button_style='',
tooltip='Description',
icon='check'
)

Output:

2

Upload Widgets

The FileUpload allows to upload any type of file(s) like a text file and any extension into memory in the kernel.

Python3
widgets.FileUpload(
accept='',
multiple=False
)

Output:

3

Frequency Slider

Import below library

Python3
import ipywidgets as widgets
from ipywidgets import HBox, VBox
import numpy as np
import matplotlib.pyplot as plt
from IPython.display import display

freq_slider = widgets.FloatSlider(
    value=3.,
    min=1.5,
    max=20.0,
    step=0.2,
    description='Frequency::',
    readout_format='.1f',
)
freq_slider

Output:

4Range_slider

Python3
range_slider = widgets.FloatRangeSlider(
    value=[-1., +1.],
    min=-10., max=+10., step=0.2,
    description='xlim:',
    readout_format='.1f',
)
range_slider

Output:

5

Grid_button

Python3
grid_button = widgets.ToggleButton(
    value=False,
    description='geeksforgeek',
    icon='check'
)
grid_button

Output:

6

Color_buttons

Python3
color_buttons = widgets.ToggleButtons(
    options=['red', 'blue', 'green','orange'],
    description='MultiColor:',
)
color_buttons

Output:

9

Title_Textbox

Python3
textbox = widgets.Text(
    value='Hello Gfg',
    description='Title_bar:',
)
textbox

Output:

10

Color_picker

Python3
picker = widgets.ColorPicker(
    concise=True,
    description='Gfg Background color:',
    value='red',
)
picker

Output:

11Using slider to data filtering

To create an IntSlider widget for filtering data within a Pandas DataFrame using a Jupyter Notebook,

Python3
import pandas as pd
import ipywidgets as widgets
from IPython.display import display

data = {
    'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve'],
    'Age': [25, 30, 35, 40, 45]
}

df = pd.DataFrame(data)

def filter_dataframe(age):
    filtered_df = df[df['Age'] >= age]
    display(filtered_df)
    
age_slider = widgets.IntSlider(
    value=df['Age'].min(),  # Set an initial value
    min=df['Age'].min(),   # Minimum age
    max=df['Age'].max(),   # Maximum age
    description='Minimum Age:'
)
widgets.interactive(filter_dataframe, age=age_slider)
display(age_slider)

Output:

ezgif-3-84855c4f99

Interactive functions

Automatically creates user interface exploring code and data.It is a perform basic operation.That provide a parameter tuning .using this method then import below Library -

from ipywidgets import interact, interactive, fixed, interact_manual

And perform a many operation,for example:-

Start a few basic function interact()

Python3
def func1(x):
    return 8+x
interact(func1, x=20);

Output:

ezgif-3-c1e5bd5a91


Python3
interact(func1, x=['good','bad','gfg','suraj']);

Output:

ezgif-2-ed6b81470a

Using Interact Ploting the graph

Python3
from ipywidgets import interact, interactive, fixed, interact_manual
import ipywidgets as widgets
import matplotlib.pyplot as plt
%matplotlib inline
import numpy as np
def plot(freq):
    x = np.linspace(0, 2*np.pi)
    y = np.sin(x * freq)
    plt.plot(x, y)
interact(plot, freq = widgets.FloatSlider(value=8.5,
                                               min=1,
                                               max=6.0,
                                               step=0.5))

Output:

ezgif-2-87730e8402

Conclusion:

Jupyter Notebook Widgets provide a strong way to build interactive and dynamic interfaces within Jupyter notebooks. They assign users to manipulate and create data in real-time, improving the data exploration and study experience. By following this educational course, you have well-informed yourself about what widgets are, their uses, and how to use them, and you have visualized an example of creating an interactive widget. Experiment with widgets to build attractive and common notebooks for your data reasoning tasks. We again performed a simple EDA task utilizing widgets, which added more convenience to visualization.


Next Article
Practice Tags :

Similar Reads

three90RightbarBannerImg