Interactive Matplotlib Plots in Jupyter With %matplotlib widget

Zoom, pan, add sliders, and respond to clicks on Matplotlib figures in JupyterLab, Notebook, VS Code, and Colab with ipympl.

To make Matplotlib plots interactive in Jupyter, install ipympl and run %matplotlib widget in a cell. Figures then have a toolbar for zooming and panning, and you can update them from sliders and mouse clicks.

Quick Example

Install the package into the same environment as your notebook, then restart Jupyter:

pip install ipympl

Run the magic command before creating a figure:

%matplotlib widget
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(4)
seconds = np.linspace(0, 60, 3000)
signal = np.sin(seconds / 3) + 0.15 * rng.standard_normal(seconds.size)
signal[(seconds > 41) & (seconds < 42)] += 1.5  # a glitch worth zooming into

fig, ax = plt.subplots(figsize=(6.5, 3.5), layout="constrained")
ax.plot(seconds, signal, linewidth=0.8, color="#0a9396")
ax.set_xlabel("Seconds")
ax.set_title("Zoom into the glitch")
plt.show()

An interactive Matplotlib figure in a notebook with a toolbar on the left and a noisy signal with a spike near 41 seconds

The toolbar appears over the left edge when you move the mouse over the figure. It has buttons for the home view, back, forward, pan, zoom to rectangle, and download. Drag the triangle in the bottom-right corner to resize the figure.

While dragging with pan or zoom, hold x or y to restrict the movement to that axis. These examples use ipympl 0.10 with Matplotlib 3.11.

Change the Toolbar and Header

The settings live on fig.canvas:

fig, ax = plt.subplots(figsize=(6.5, 3.5), layout="constrained")
fig.canvas.toolbar_position = "top"    # "left", "right", "top", "bottom"
fig.canvas.toolbar_visible = True      # always shown, instead of fading in
fig.canvas.header_visible = False      # hide the "Figure 2" label
fig.canvas.footer_visible = False      # hide the cursor coordinates
ax.plot(seconds, signal, linewidth=0.8, color="#ca6702")
plt.show()

An interactive figure with the toolbar fixed along the top and no figure label

Update a Plot With Sliders

Draw the line once, then change its data when a slider moves. ipywidgets is installed along with ipympl.

import ipywidgets as widgets

t = np.linspace(0, 10, 500)

def wave(frequency, damping):
    return np.exp(-damping * t) * np.sin(2 * np.pi * frequency * t)

with plt.ioff():  # don't show the figure until we place it
    fig, ax = plt.subplots(figsize=(6.5, 3.5), layout="constrained")
fig.canvas.header_visible = False
(line,) = ax.plot(t, wave(0.6, 0.2), color="#9b2226", linewidth=2)
ax.set_ylim(-1.05, 1.05)

frequency = widgets.FloatSlider(value=0.6, min=0.1, max=2, step=0.1, description="Frequency")
damping = widgets.FloatSlider(value=0.2, min=0, max=1, step=0.05, description="Damping")

def update(change):
    line.set_ydata(wave(frequency.value, damping.value))
    fig.canvas.draw_idle()

frequency.observe(update, names="value")
damping.observe(update, names="value")

widgets.VBox([frequency, damping, fig.canvas])

Two sliders for frequency and damping above a damped sine wave that updates as they move

Three things make this work:

  • plt.ioff() stops the figure from appearing on its own, so it isn't shown twice.
  • line.set_ydata() changes the existing line, which is faster and smoother than clearing and replotting.
  • fig.canvas.draw_idle() asks for a redraw.

The VBox has to be the last line of the cell, or be passed to display().

Respond to Clicks

fig.canvas.mpl_connect() calls your function on mouse and keyboard events. This example adds a point wherever you click and fits a line once there are two:

with plt.ioff():
    fig, ax = plt.subplots(figsize=(6.5, 3.8), layout="constrained")
fig.canvas.header_visible = False
ax.set(xlim=(0, 10), ylim=(0, 10), title="Click to add points")
points = []
dots = ax.scatter([], [], s=60, color="#005f73", zorder=3)
(fit,) = ax.plot([], [], color="#ee9b00", linewidth=2)

def on_click(event):
    # Ignore clicks outside the plot, and clicks made while zooming or panning
    if event.inaxes != ax or fig.canvas.toolbar.mode:
        return
    points.append((event.xdata, event.ydata))
    xy = np.array(points)
    dots.set_offsets(xy)
    if len(points) > 1:
        slope, intercept = np.polyfit(xy[:, 0], xy[:, 1], 1)
        ends = np.array([0, 10])
        fit.set_data(ends, slope * ends + intercept)
        ax.set_title(f"y = {slope:.2f}x + {intercept:.2f}")
    fig.canvas.draw_idle()

connection = fig.canvas.mpl_connect("button_press_event", on_click)
fig.canvas

An interactive scatter plot with five clicked points, a fitted line and its equation in the title

Call fig.canvas.mpl_disconnect(connection) to stop listening. Errors raised inside a callback may not appear under the cell, so check Jupyter's log console if a click seems to do nothing.

widget vs inline vs notebook

Magic What you get
%matplotlib inline Static PNG images (the default in notebooks)
%matplotlib widget Interactive figures through ipympl, in JupyterLab and Notebook 7
%matplotlib notebook The old interactive backend, only for Notebook versions before 7; it doesn't work in JupyterLab
%matplotlib qt A separate desktop window on the machine running the kernel

Run %matplotlib inline to switch back. For interactive charts that stay interactive in a shared HTML file, Plotly is a better fit, since ipympl needs a running Python kernel.

Use It in Google Colab and VS Code

Colab needs third-party widgets switched on before the first figure:

from google.colab import output
output.enable_custom_widget_manager()
%matplotlib widget

In VS Code, install ipympl into the kernel you selected for the notebook, with the Jupyter extension enabled, then use the same magic command.

Fix Common Problems

Symptom Fix
'widget' is not a recognised GUI loop or backend name or No module named 'ipympl' Install ipympl in the kernel's environment (%pip install ipympl) and restart the kernel
"Error displaying widget" or text such as Canvas(...) Restart Jupyter and reload the browser tab. If Jupyter runs from a different environment than the kernel, install ipympl in both
The figure appears twice Create it inside with plt.ioff():
Warnings about too many open figures Close old ones with plt.close("all")
Plots are still static Run %matplotlib widget before creating the figure

For blank output outside of widgets, see why a Matplotlib plot isn't showing.

Similar Topics