Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to make static SVG plot (from matplotlib) interactive via the browser

My goal is to make a plot that you can interact with in the browser. Ideally, I would like a well-documented and mature JavaScript plotting library that supports SVG. As far as I can tell, this doesn't exist, though please correct me if I'm wrong.

I've identified a couple alternatives.

  1. Use a JavaScript graphics library (e.g. Raphael) and draw everything from scratch. This seems like a lot of unnecessary, tedious work.
  2. Use a plotting library to produce SVG, then use JavaScript to support interaction. This seems more manageable, though I do have the following problem: How can I add metadata to the SVG from the plotting library (matplotlib)? This metadata would not be shown when the SVG is displayed, but it would be accessible from JavaScript.

Any advice is much appreciated.

like image 247
David Avatar asked Jan 24 '12 21:01

David


People also ask

How do I save matplotlib figures as SVG?

To save the file in SVG format, use savefig() method where image name is myImagePDF. svg, format="svg". To show the image, use plt. show() method.

What is matplotlib interactive mode?

matplotlib supports interactive mode. In this mode, you don't have to have to use plt. show() to display the plot or plt. draw() to update it. When interactive mode is on, the backend in charge of applying changes to your plot will automatically pop up and update the plot when you do.

Does matplotlib support SVG?

But Matplotlib cannot work directly with svg content.

Is Plotly better than matplotlib?

Plotly has several advantages over matplotlib. One of the main advantages is that only a few lines of codes are necessary to create aesthetically pleasing, interactive plots. The interactivity also offers a number of advantages over static matplotlib plots: Saves time when initially exploring your dataset.


1 Answers

One way to this can be seen in the matplotlib gallery.

Basically:

  1. In matplotlib, use element.set_gid("youridhere") on the matplotlib element you wish to make interactive. That is, use set_gid() on the output from plot()/hist()/whatever().
  2. Create an svg with matplotlib, but use a StringIO object as your file.
  3. Parse the svg with an xml library (e.g. xml.etree.ElementTree)
  4. Find the xml elements with the id that you set (e.g. "youridhere").
  5. Add onclick/on${theeventyoucareabout} attributes with a javascript function name.
  6. Add a script element with your javascript as a CDATA to the xml tree.
  7. Export the xml to an svg file!
like image 173
Tim Swast Avatar answered Sep 20 '22 19:09

Tim Swast