Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib svg as string and not a file

I'd like to use Matplotlib and pyplot to generate an svg image to be used in a Django framework. as of now I have it generating image files that are link to by the page, but is there a way to directly get with the svg image as a unicode string without having to write to the file system?

like image 485
ciferkey Avatar asked Mar 28 '11 00:03

ciferkey


1 Answers

Try using StringIO to avoid writing any file-like object to disk.

import matplotlib.pyplot as plt
import StringIO
from matplotlib import numpy as np

x = np.arange(0,np.pi*3,.1)
y = np.sin(x)

fig = plt.figure()
plt.plot(x,y)

imgdata = StringIO.StringIO()
fig.savefig(imgdata, format='svg')
imgdata.seek(0)  # rewind the data

svg_dta = imgdata.buf  # this is svg data

file('test.htm', 'w').write(svg_dta)  # test it
like image 56
Paul Avatar answered Nov 16 '22 03:11

Paul