Matplotlib svg作为字符串而不是一个文件 [英] Matplotlib svg as string and not a file

查看:350
本文介绍了Matplotlib svg作为字符串而不是一个文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Matplotlib和pyplot来生成一个要在Django框架中使用的svg图像。到目前为止,我已经生成了页面链接的图像文件,但是有没有办法直接将svg图像作为unicode字符串,而不必写入文件系统?

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?

推荐答案

尝试使用 StringIO 避免将任何类似文件的对象写入磁盘。

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

这篇关于Matplotlib svg作为字符串而不是一个文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆