gpt4 book ai didi

python - 使用 matplotlib savefig 保存文件对象,从多个 svg 图形创建 tar 文件

转载 作者:行者123 更新时间:2023-12-04 14:23:32 25 4
gpt4 key购买 nike

我使用 python 和 matplotlib 创建了多个图形。 PyQt5 用作显示图形的后端。我正在使用 savefig 以 svg 格式保存图形。

我的问题是我想创建一个包含所有 svg 文件的 zip 文件。我所拥有的简化版本是:

import matplotlib
figure = matplotlib.figure.Figure(dpi=72)
canvas = matplotlib.backends.backend_qt5agg.FigureCanvasQTAgg(figure)
axes = figure.add_axes((0.1, 0.15, 0.85, 0.8))
axes.plot(data)
# Do all of that three times to give me three separate figures
# (let's call them figure, figure1 and figure2)

现在我可以使用以下方法保存每个图形

figure.savefig(filename, format='svg')
figure1.savefig .....

但我其实很想拥有类似的东西

fileobject = figure.savefig(format='svg')

我可以在其中使用 tarfile 模块将所有 fileobject 压缩并存储在一个存档中。我目前的解决方法是保存文件,读取它们并使用这些对象创建 tar 文件,然后删除原件。有一个更直接的方法来做到这一点会很好......

最佳答案

你可以使用 buffered stream将文件保存到。像这样的东西:

import io

fileobject1 = io.BytesIO()
figure1.savefig(fileobject1, format='svg')

fileobject2 = io.BytesIO()
figure2.savefig(fileobject2, format='svg')

等等

关于python - 使用 matplotlib savefig 保存文件对象,从多个 svg 图形创建 tar 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50853632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com