6

I am trying to embed a SVG image within a matplotlib subplot.

matplotlib can only read PNGs natively, but if PIL is installed, it will use it to load the image and return an array (if possible) which can be used with imshow(). http://matplotlib.sourceforge.net/api/pyplot_api.html

import Image     
filename = "/tmp/figure.svg"
pil_img = Image.open(filename) # PIL image
img = np.asarray(pil_img) # converting PIL image into numpy array
self.axes.cla()
self.axes.imshow(img)

But of course PIL does not support SVG. The error:

File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 1980, in open

raise IOError("cannot identify image file")

IOError: cannot identify image file

How can I rasterize the SVG file to plot using imshow or directly plot the vectors using matplotlib?

Thanks.

3
  • related, but not an answer. stackoverflow.com/questions/3600164/… Commented Aug 29, 2012 at 22:44
  • also: stackoverflow.com/questions/6589358/… Commented Aug 29, 2012 at 22:48
  • Depends how complex your SVG is. If it is a simple one, you could try parsing it with the standard python xml libraries and creating native matplotlib artists? Might be a fair bit of work though... Sorry I don't really have a good answer for this one. Commented Oct 4, 2012 at 19:37

1 Answer 1

2

I also had the same problem but now implemented a solution in my package pylustrator: https://pylustrator.readthedocs.io/en/latest/composing.html#svg-files

It can read and parse svg files and creates matplotlib artists to display the svg content in the figure.

Not all svg feature can be emulated by matplotlib artists, so e.g. gradients or filters will not be displayed, but the majority of svg features are supported.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.