Interactive matplotlib figures in the IPython notebook - they've landed!

2014

June

3

Tags: matplotlib (4), Python (10)

After what feels like years chipping away at the problem, not least from some awesome developers including the whole of the IPython development team, Michael Droetboom and Jason Grout, I recently closed the development loop and added a new matplotlib backend providing interactive figures in the IPython notebook environment.

The "nbagg" backend makes use of the familiar anti-grain geometry rendering engine, so your figures will render as they always have with other agg based backends, with the key difference that instead of an interactive GUI upon show, an inline interactive figure is displayed, complete with the "pan/zoom" and "zoom to rectangle" buttons, as can be seen in the following screenshot:

screenshot

The backend itself is still very much a work in progress, but it is functional, and well worth trying out for yourself. Turning the backend on with v1.4+ of matplotlib (not yet released at time of writing) is as simple as:

In [1]:
import matplotlib 

matplotlib.use('nbagg')

Now that we've changed the backend, we can go ahead and import pyplot and produce a figure as normal:

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

plt.plot(np.sin(np.linspace(0, 2*np.pi)))
plt.show()

To avoid re-writing the matplotlib rendering engine in a browser compatible language (i.e. JavaScript), the nbagg backend requires a live IPython session for interactive figures. Notice however that in this static rendering of the notebook, we have a static image of the figure, akin to the existing IPython "inline" backend. As with the "inline" backend, it is only the snapshot of the figure which is preserved, rather than the figure instance itself (the ability to pickle a figure does make that a possibility though) - essentially, what this means is that we have an opportunity to interact with out data before the figure is cast in stone as an image.

Features

The "nbagg" backend has some pretty unique features which have the potential to be built upon in the future.

One interesting feature of a nbagg figure is that it can be displayed multiple times, with all views on the figure being updated simultaneously (even accross different browsers), so there is a real potential for some collaborative figure investigation when the concept of shared users becomes a reality in the notebook.

I'm keen to make this backend easy to extend such that its easy to add things such as an "export to mpld3" button, some snapshotting functionality so that notebook viewers can see multiple views of the same figure in a slideshow and I'm sure there is a whole host of other cool functionality that could be added.

Let me know what you think? Got any ideas on how to make this backend even better? Get in touch in the comments section.