Matplotlib svg as string and not a file Matplotlib svg as string and not a file django django

Matplotlib svg as string and not a file


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

import matplotlib.pyplot as pltimport StringIOfrom matplotlib import numpy as npx = 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 datasvg_dta = imgdata.buf  # this is svg datafile('test.htm', 'w').write(svg_dta)  # test it


Here is python3 version

import matplotlib.pyplot as pltimport numpy as npimport iof = io.BytesIO()a = np.random.rand(10)plt.bar(range(len(a)), a)plt.savefig(f, format = "svg")print(f.getvalue()) # svg string