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
import matplotlib.pyplot as plt
import numpy as np
import io
f = io.BytesIO()
a = np.random.rand(10)
plt.bar(range(len(a)), a)
plt.savefig(f, format = "svg")
print(f.getvalue()) # svg string
from io import StringIO
import matplotlib.pyplot as plt
def plot_to_svg() -> str:
"""
Saves the last plot made using ``matplotlib.pyplot`` to a SVG string.
Returns:
The corresponding SVG string.
"""
s = StringIO()
plt.savefig(s, format="svg")
plt.close() # https://stackoverflow.com/a/18718162/14851404
return s.getvalue()
a = [10, 20, 5]
plt.bar(range(len(a)), a)
svg = plot_to_svg()
print(svg)
3条答案
按热度按时间voase2hg1#
尝试使用
StringIO
来避免将任何类似文件的对象写入磁盘。字符串
juzqafwq2#
python3版本
字符串
0mkxixxg3#
基于abasar's answer,我提出以下代码片段:
字符串