In my googling, I’ve found a few solutions to this issue. None are perfect for what I was hoping to do (have Django and MPL work together to produce a nice interactive figure) but I did come across some interesting tools.
The ‘webagg’ backend for matplotlib
This was the solution I was expecting to work. When you specify the webagg backend after importing matplotlib, running f.show() starts up a mini web server and opens the plot in your default browser. As far as I can tell, the plot has the full functionality you’d get with any of the traditional backends.
The magic of having full interactivity in the browser relies on the figure staying connected to the python kernel, which is non-trivial to set up on a live website. I haven’t found any instructions that a non-expert can follow to set this up on a personal website.
mpld3 is a python package that converts your matplotlib code into d3.js code. It’s great! Instead of
f.show(), you can run
mpld3.save_html(f, 'test.html') and you have a html snippet that can be inserted into a webpage. The plot below is just vanilla matplotlib saved with mpld3.save_html.
The plots look great and you get the default panning/zooming functions you expect in MPL. However widgets don’t work so you don’t get the full interactive experience. mpld3 does have some plugins, so for example you can get tooltips when hovering over plot elements. This is great, but requires some non-MPL code. Below I’ve added a hover tooltip which displays the label of a line plot when you hover over it. Very neat, but still not quite matplotlib’s picker.
The mpld3 website has a tutorial on writing your own plugins, and it looks like there’s very little stopping you from recreated any feature you want as long as you know d3.js. I really appreciate all the work that’s gone into mpld3, but it’s still missing some pretty important features. For example, you might have noticed the years in the x-axis tick labels have a comma in them, which would be easily fixable in vanilla MPL with
ax.xaxis.set_ticklabels(). But mpld3 doesn’t (yet?) have support for setting ticklabels, so you’re stuck with whatever shows up. A small price to pay for the ease of use, but still noticeable.
Bokeh is a python visualization library that targets web browsers. It looks like it’s further along in development than mpld3, however it’s not trivially convertible from matplotlib. There is a bokeh.mpl module, but it is no longer maintained and is considered deprecated. I haven’t tried Bokeh myself yet, but if I was going make web visuals a major focus and wanted to stick with python, this is probably where I’d end up.
import plotly.plotly as py
import plotly.tools as tls
import plotly.offline as plo
plotly_fig = tls.mpl_to_plotly( f )