Sloppy SVG generated by matplotlib resulting on poor clipping of datapoint drawing in figures

Viewed 1912

Figures that I create with matplotlib do not properly clip points to the figure axes when rendered, but instead draw additional points, even though such figures look fine in some viewers.

For example (following an example from the documentation) using

import matplotlib
matplotlib.use('SVG')
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig = plt.figure()
ax = fig.add_subplot(111)
x, y = 12*np.random.rand(2, 1000)
ax.set(xlim=[2,10])
ax.plot(x, y, 'go')  # plot some data in data coordinates

circ = patches.Circle((0.5, 0.5), 0.25, transform=ax.transAxes,
                      facecolor='yellow', alpha=0.5)
ax.add_patch(circ)

plt.savefig()

I seem, when viewed for example in OS X Preview, to get

enter image description here

but when I view it in other editors, such as iDraw I get a mess (where, weirdly, there is a combination of correct clipping of edge points, failed clipping of points outside the axes, and clipping of the canvass at a point that does not correspond to either the axes or the range of data):

enter image description here

I'm not experienced with SVG, but those I've asked tell me that

I looked at the SVG file and didn't like what I saw. Characters are flattened, and definition sections are scattered throughout the file instead of being at the top; some defs are inside graphics constructs. There's a lot of cruft. It turns out the definition of the clip-path is at the very end of the svg file -- after all the uses ...

How can I get matplotlob to generate SVG that does not have these issues? I know that I can edit the SVG, but I have no idea how, and doing so defeats the purpose and I hope that it is not necessary to add a "by hand" step to my workflow.


I'm interested in understanding what the cause of the sloppy SVG generated by matplotlib is: whether it's something that can be avoided by coding a bit differently (though not, clearly, by simply checking whether every data point is in range), or whether it's a bug in matplotlib (or perhaps whether it's just a problem with ambiguities in the SVG standard). The goal is getting matplotlob to generate SVG that is not buggy.

1 Answers
Related