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

标签 python matplotlib svg tarfile

我使用 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/

相关文章:

python - 使用 PyQt5 和 Matplotlib 制作动态图

matplotlib - 设置 mpld3 图的高度和宽度

python - 如何为 matplotlib 中的圆圈分配颜色?

javascript - D3.js:如何在 "if..else"语句后更改 xlink:href 图像

html - IE11 无法通过 Web 服务器显示带有对象标签的图像,但在本地可以正常显示

python - 无法使用 pyaudio 录制多个波形(无默认输出设备)

python - Applescript 使用了错误的 python 版本,如何更改?

python - 按列值在 DataFrame 切片上查找计算函数的最快方法(Python pandas)

javascript - 使用 D3.js 将 SVG 元素附加到 HTML 表格单元格

python - 如何将所有 conda 环境放入一个文件夹