2011-03-28 65 views
11

我想使用Matplotlib和pyplot來生成一個在Django框架中使用的svg圖像。截至目前,我有它生成的圖像文件鏈接到頁面,但有沒有辦法直接獲得svg圖像作爲unicode字符串,而不必寫入文件系統?Matplotlib svg作爲字符串而不是文件

回答

16

嘗試使用StringIO來避免將任何類似文件的對象寫入磁盤。

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 
+1

這或許值得指出的是'cStringIO.StringIO()'提供了更快的,但同樣的事情不太靈活的版本,以及。 http://docs.python.org/library/stringio.html#module-cStringIO如果OP實際上要在生產代碼中使用它,它可能會有所作爲(或不是!)。無論如何,一個'StringIO'類文件對象肯定是要走的路。 – 2011-03-28 15:22:27

相關問題