The Matplotlib Jupyter Widget Backend

Enabling interaction with matplotlib charts in the Jupyter notebook and JupyterLab

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


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

In [4]:
# Testing matplotlib interactions with a simple plot

import matplotlib.pyplot as plt
import numpy as np

plt.figure(1)
plt.plot(np.sin(np.linspace(0, 20, 100)))
plt.show()



In [12]:
# A more complex example from the matplotlib gallery

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)

n_bins = 10
x = np.random.randn(1000, 3)

fig, axes = plt.subplots(nrows=2, ncols=2)
ax0, ax1, ax2, ax3 = axes.flatten()

colors = ['red', 'tan', 'lime']
ax0.hist(x, n_bins, density=1, histtype='bar', color=colors, label=colors)
ax0.legend(prop={'size': 10})
ax0.set_title('bars with legend')

ax1.hist(x, n_bins, density=1, histtype='bar', stacked=True)
ax1.set_title('stacked bar')

ax2.hist(x, n_bins, histtype='step', stacked=True, fill=False)
ax2.set_title('stack step (unfilled)')

# Make a multiple-histogram of data-sets with different length.
x_multi = [np.random.randn(n) for n in [10000, 5000, 2000]]
ax3.hist(x_multi, n_bins, histtype='bar')
ax3.set_title('different sample sizes')


fig.tight_layout()
plt.show()



In [13]:
# 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])



In [ ]: