All examples By author By category About

chornbaker

Matplotlib Scatterplot in D3

Matplotlib Scatterplot in D3

This is a useful example for converting a matplotlib scatterplot to D3 with an initial animation. Using this template, you can quickly generate a dynamic scatterplot using all of your favorite matplotlib styles, and add more advanced interactions without dealing with a lot of additional formatting.

See scatterplot.py for code used to generate scatterplot.svg. It generates a simple scatterplot with some basic formatting. Matplotlib's savefig function will automatically output an svg format if the filepath has a .svg extension. The key is to assign a unique gid to each dot using the gid parameter, so it is simple to find the dots when you read the svg in index.html.

Assigning a gid to individual matplotlib elements is fairly simple for lines and bars, but a bit more complicated for scatterplots, since they are stored in a PathCollection object. As a workaround for this, I write the svg to StringIO and use BeautifulSoup find and add the id to each dot before saving the output file.

This is Part 3 in a series of examples for using matplotlib generated plots in D3.