Mastering Matplotlib: Part 7 — Introduction to Interactive Backends
Enhancing Your Data Visualization Experience with Dynamic Features

🔙 Previous: Exploring 3D Plotting
🔜 Next: Styling Your Plots with Matplotlib
Note: You can find all the code examples for Matplotlib series in my GitHub repository.
Matplotlib supports several interactive backends that allow you to create plots that respond to user input, such as clicks, scrolls, and drags. The choice of backend depends on your environment:
- TkAgg: Default backend for standard Python environments.
- Qt5Agg: A popular backend for desktop applications.
- ipympl: A backend designed for Jupyter Notebooks, providing interactive plots directly in the notebook.
Interactive backends enable features like zooming, panning, and dynamic updates, making your visualizations more engaging. Panning refers to the ability to move or slide across a visualization to view different portions of the data without changing the zoom level.
1. Using ipympl for Jupyter Notebooks
The ipympl backend is ideal for creating interactive plots in Jupyter Notebooks. It integrates seamlessly with the notebook interface, allowing you to interact with your plots directly within the notebook cells.
Installation and Setup
First, you need to install the ipympl package:
pip install ipympl
Note: You may need to restart the kernel to use updated packages.
To activate the ipympl backend in a Jupyter Notebook, include the following magic command at the beginning of your notebook:
%matplotlib widget
This command enables interactive plotting for the entire notebook session.
Creating an Interactive Plot
Let’s create a simple interactive plot using ipympl:
import matplotlib.pyplot as plt
import numpy as np
# Activate the ipympl backend
%matplotlib widget
# Generate some data
x = np.linspace(0, 10, 100)
y = np.sin(x)
# Create an interactive plot
fig, ax = plt.subplots()
line, = ax.plot(x, y)
# Add interactivity
ax.set_title('Interactive Sine Wave')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
plt.show()Output:

With this setup, you can zoom, pan, and adjust the plot interactively within the notebook.
2. Creating Interactive Widgets
Interactive widgets allow users to manipulate plot elements dynamically, providing a richer experience in data exploration.
Using ipywidgets
ipywidgets is a popular library for adding interactive widgets to Jupyter Notebooks. It integrates smoothly with Matplotlib to control plot parameters.
pip install ipywidgets
Example: Interactive Plot with Sliders
Let’s combine Matplotlib with ipywidgets to create a more interactive plotting environment:
import numpy as np
import matplotlib.pyplot as plt
import ipywidgets as widgets
# Activate ipympl backend
%matplotlib widget
x = np.linspace(0, 10, 100)
def update_plot(frequency, amplitude):
y = amplitude * np.sin(frequency * x)
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_title(f'Sine Wave - Frequency: {frequency}, Amplitude: {amplitude}')
plt.show()
frequency_slider = widgets.FloatSlider(value=1, min=0.1, max=5, step=0.1, description='Frequency:')
amplitude_slider = widgets.FloatSlider(value=1, min=0.5, max=2, step=0.1, description='Amplitude:')
widgets.interact(update_plot, frequency=frequency_slider, amplitude=amplitude_slider)Output:

This setup allows users to adjust the frequency and amplitude sliders, with the plot updating in real time.
3. Additional Interactive Features
Adding Tooltips with mplcursors
mplcursors is a Matplotlib extension that adds interactive data cursors (tooltips) to your plots, providing more information about data points on hover.
I copied an example from the official website of mplcursors. For more information, please refer to this amazing website.
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
%matplotlib widget
# Create a 2D array by computing the outer product of two ranges
data = np.outer(range(10), range(1, 5))
fig, ax = plt.subplots()
lines = plt.plot(data)
ax.set_title("Click somewhere on a line.\nRight-click to deselect.\n"
"Annotations can be dragged.")
mplcursors.cursor(lines) # or just mplcursors.cursor()
mplcursors.cursor()
plt.show()Output:

Conclusion
In this seventh part of the Mastering Matplotlib series, we explored the world of interactive plotting. We started by introducing interactive backends and demonstrated how to use different ways to create interactive plots in Jupyter Notebooks. We then delved intoipywidgets to create dynamic plots with interactive controls. Finally, we added an extra layer of interactivity with tooltips using mplcursors. These interactive tools are powerful additions to your data visualization toolkit, enabling you to create more engaging and user-friendly plots.
In the next part of the series, we’ll explore even more advanced plotting techniques and customizations to further enhance your visualizations. Here’s what you can look forward to:
- Styling with Matplotlib: Learn how to improve the aesthetics of your plots using various styling options.
- Using Built-in Styles with
plt.style.use(): Discover the built-in styles available in Matplotlib and how to apply them to your plots for quick enhancements. - Creating Custom Styles: Find out how to define your own styles to maintain consistency across your visualizations.
- Saving and Sharing Styles: Understand how to save your custom styles and share them with others, making collaboration easier.
If you like the article and would like to support me make sure to:
👏 Clap for the story (as much as you liked it 😊) and follow me 👉 📰 View more content on my medium profile 🔔 Follow Me: LinkedIn | Medium | GitHub | Twitter
Feel free to share your thoughts and questions in the comments below!




