This is one of the 100 recipes of the IPython Cookbook, the definitive guide to high-performance scientific computing and data science in Python.

6.5. Converting matplotlib figures to d3.js visualizations with mpld3

  1. First, we load NumPy and matplotlib as usual.
In [ ]:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline
  1. Then, we enable the mpld3 figures in the notebook with a single function call.
In [ ]:
from mpld3 import enable_notebook
enable_notebook()
  1. Now, let's create a scatter plot with matplotlib.
In [ ]:
X = np.random.normal(0, 1, (100, 3))
color = np.random.random(100)
size = 500 * np.random.random(100)
plt.figure(figsize=(6,4))
plt.scatter(X[:,0], X[:,1], c=color,
            s=size, alpha=0.5, linewidths=2)
plt.grid(color='lightgray', alpha=0.7)

The matplotlib figure is rendered with d3.js instead of the standard matplotlib backend. In particular, the figure is interactive (pan and zoom).

  1. Now, we create a more complex example with multiple subplots representing different 2D projections of a 3D dataset. We use the sharex and sharey keywords in matplotlib's subplots function to automatically bind the x and y axes of the different figures. Panning and zooming in any of the subplots automatically updates all the other subplots.
In [6]:
fig, ax = plt.subplots(3, 3, figsize=(6, 6),
                       sharex=True, sharey=True)
fig.subplots_adjust(hspace=0.3)
X[::2,2] += 3
for i in range(3):
    for j in range(3):
        ax[i,j].scatter(X[:,i], X[:,j], c=color,
            s=.1*size, alpha=0.5, linewidths=2)
        ax[i,j].grid(color='lightgray', alpha=0.7)

This use case is perfectly handled by mpld3: the d3.js subplots are also dynamically linked together.

You'll find all the explanations, figures, references, and much more in the book (to be released later this summer).

IPython Cookbook, by Cyrille Rossant, Packt Publishing, 2014 (500 pages).