如何将 Matplotlib 图表保存为 SVG 字符串
你可以使用 StringIO 将 Matplotlib 图表保存为字符串,而无需保存到中间文件:
save_plot_to_string.py
from matplotlib import pyplot as plt
plt.plot([0, 1], [2, 3]) # 只是一个最小展示
# 将图表保存到 StringIO
from io import StringIO
i = StringIO()
plt.savefig(i, format="svg")
# 如何访问字符串
print(i.getvalue())注意除非你保存到文件,否则在调用 plt.savefig() 时需要设置 format=... 参数。如果保存到文件,Matplotlib 将尝试从文件名扩展名(如 .svg)推导格式
Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow