The Matplotlib Jupyter Widget Backend

Enabling interaction with matplotlib charts in the Jupyter notebook and JupyterLab

https://github.com/matplotlib/jupyter-matplotlib


In [ ]:
# Enabling the `widget` backend.
# This requires jupyter-matplotlib a.k.a. ipympl.
# ipympl can be install via pip or conda.
%matplotlib widget

In [ ]:
import matplotlib.pyplot as plt
import numpy as np

In [ ]:
# When using the `widget` backend from ipympl,
# fig.canvas is a proper Jupyter interactive widget, which can be embedded in
# Layout classes like HBox and Vbox.

# One can bound figure attributes to other widget values.

from ipywidgets import HBox, FloatSlider

plt.ioff()
plt.clf()

slider = FloatSlider(
    orientation='vertical',
    value=1.0,
    min=0.02,
    max=2.0
)

fig = plt.figure(3)

x = np.linspace(0, 20, 500)

lines = plt.plot(x, np.sin(slider.value  * x))

def update_lines(change):
    lines[0].set_data(x, np.sin(change.new * x))
    fig.canvas.draw()
    fig.canvas.flush_events()

slider.observe(update_lines, names='value')

HBox([slider, fig.canvas])