Advanced Features Intermediate
Take your Jupyter skills to the next level with interactive widgets, dynamic plots, notebook extensions, format conversion, parameterized execution, and testing strategies.
Widgets (ipywidgets)
Create interactive controls that let users adjust parameters without modifying code:
# Install ipywidgets
pip install ipywidgets
# Interactive slider
import ipywidgets as widgets
from IPython.display import display
slider = widgets.IntSlider(value=5, min=0, max=10, description='Value:')
display(slider)
# Interactive function with @interact
from ipywidgets import interact
@interact(x=(0, 10, 1), color=['red', 'blue', 'green'])
def plot_line(x=5, color='blue'):
import matplotlib.pyplot as plt
plt.plot([0, x], [0, x**2], color=color, linewidth=2)
plt.title(f'x = {x}')
plt.show()
# Dropdown
dropdown = widgets.Dropdown(
options=['Linear', 'Polynomial', 'RBF'],
value='Linear',
description='Kernel:'
)
# Button
button = widgets.Button(description='Run Analysis')
button.on_click(lambda b: print("Analysis running..."))
# Link widgets together
text = widgets.FloatText()
slider = widgets.FloatSlider()
widgets.link((text, 'value'), (slider, 'value'))
display(text, slider)
Interactive Plots
Plotly
import plotly.express as px
df = px.data.iris()
fig = px.scatter(df, x='sepal_width', y='sepal_length',
color='species', hover_data=['petal_length'])
fig.show()
Bokeh
from bokeh.plotting import figure, show
from bokeh.io import output_notebook
output_notebook()
p = figure(title="Interactive Plot", width=600, height=400)
p.circle([1, 2, 3, 4, 5], [6, 7, 2, 4, 5], size=15, color="navy", alpha=0.5)
show(p)
Extensions (nbextensions)
Notebook extensions add powerful features to the classic interface:
# Install nbextensions
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
# Enable the configurator
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user
| Extension | Description |
|---|---|
| Table of Contents | Auto-generated navigable TOC from Markdown headings |
| Code Folding | Collapse/expand code blocks for cleaner viewing |
| Spell Checker | Spell check for Markdown cells |
| ExecuteTime | Show execution time for each cell |
| Collapsible Headings | Collapse sections under headings |
| Variable Inspector | Panel showing all variables and their values |
| Autopep8 | Auto-format code to PEP 8 style |
| Scratchpad | A floating cell for quick experiments |
Custom CSS/HTML
from IPython.display import HTML, display
# Custom styling
display(HTML("""
<style>
.custom-box { background: #f0f7ff; border-left: 4px solid #4285F4;
padding: 15px; margin: 10px 0; border-radius: 4px; }
</style>
<div class="custom-box">
<strong>Custom Info Box</strong>
<p>You can inject custom HTML and CSS directly into notebooks.</p>
</div>
"""))
Parameterized Notebooks (Papermill)
Run notebooks programmatically with different parameters:
# Install papermill
pip install papermill
# Tag a cell as "parameters" in notebook metadata
# Then run from command line:
papermill input.ipynb output.ipynb -p learning_rate 0.01 -p epochs 50
# Or from Python:
import papermill as pm
pm.execute_notebook(
'template.ipynb',
'output_experiment_1.ipynb',
parameters=dict(learning_rate=0.01, batch_size=32, epochs=50)
)
nbconvert (Export Notebooks)
# Convert to HTML
jupyter nbconvert --to html notebook.ipynb
# Convert to PDF (requires LaTeX)
jupyter nbconvert --to pdf notebook.ipynb
# Convert to slides (reveal.js)
jupyter nbconvert --to slides notebook.ipynb --post serve
# Convert to Python script
jupyter nbconvert --to script notebook.ipynb
# Convert to Markdown
jupyter nbconvert --to markdown notebook.ipynb
# Convert without code (documentation only)
jupyter nbconvert --to html --no-input notebook.ipynb
Testing Notebooks
# Using nbval for pytest
pip install nbval
pytest --nbval my_notebook.ipynb
# Using nbmake
pip install nbmake
pytest --nbmake my_notebook.ipynb
# Assertions within notebooks
assert len(df) > 0, "DataFrame should not be empty"
assert model_accuracy > 0.8, f"Accuracy {model_accuracy} is below threshold"
Parallel Execution
# Run multiple notebooks in parallel with papermill
import papermill as pm
from concurrent.futures import ProcessPoolExecutor
configs = [
{'lr': 0.001, 'batch': 32},
{'lr': 0.01, 'batch': 64},
{'lr': 0.1, 'batch': 128},
]
def run_experiment(config):
pm.execute_notebook('template.ipynb', f'output_lr{config["lr"]}.ipynb',
parameters=config)
with ProcessPoolExecutor(max_workers=3) as executor:
executor.map(run_experiment, configs)
Ready to Go Deeper?
Live instructor-led courses from our partners. Affiliate disclosure.
AI & ML Courses - 30% Off
Live instructor-led AI, machine learning, data science, and cloud courses for working professionals. Use code Limited30 at checkout.
EdurekaDataCamp - AI & Data Science
Hands-on Python, machine learning, and AI courses with interactive exercises and real projects.
DataCampedX - Top AI Courses
University-level AI courses from MIT, Harvard, Stanford. Earn certificates that employers recognize.
edX